You need to enable JavaScript to run this app. 如何不使用正则表达式从字符串中提取hashtag并拆分连续#标签
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用正则表达式从字符串中提取hashtag并拆分连续#标签

问题根因

原代码仅按空格对字符串做拆分,再判断拆分后的片段首字符是否为#,没有处理同一个空格分隔段内包含多个#的场景,所以类似#Computer#Science的内容只会被识别为单个tag,返回Computer#Science,不符合预期。

实现思路

  • 改为逐字符遍历整个字符串识别#符号,不依赖空格拆分
  • 每次遇到#时,如果上一个tag还没保存,先把已收集的上一个tag存入结果列表,再开启新tag的收集
  • 收集tag过程中遇到空格或者新的#就结束当前tag的收集
  • 遍历结束后检查是否存在未存入列表的剩余tag,避免遗漏

优化后代码

def extract_hashtag(s):
    result = []
    current_tag = []
    in_tag = False
    for char in s:
        if char == '#':
            # 遇到新的#,先保存上一个未完成的tag
            if in_tag and current_tag:
                result.append(''.join(current_tag))
                current_tag.clear()
            in_tag = True
        elif char.isspace():
            # 遇到空格结束当前tag收集
            if in_tag and current_tag:
                result.append(''.join(current_tag))
                current_tag.clear()
            in_tag = False
        else:
            # 处于tag收集状态就追加当前字符
            if in_tag:
                current_tag.append(char)
    # 处理字符串末尾剩余的tag
    if in_tag and current_tag:
        result.append(''.join(current_tag))
    return result

测试结果

输入测试用例:"Python is #great #Computer#Science"
函数返回:['great', 'Computer', 'Science'],完全符合预期。

内容的提问来源于stack exchange,提问作者Help

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:06:03