You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则提取特定格式字符串中的标题内容?

提取标题字符串的解决方案
  • 你用的正则r'title:(\w+\s)'只匹配到"How",是因为\w+仅能匹配字母、数字和下划线,遇到空格就停止匹配,没法覆盖带空格和特殊符号的完整标题。
  • 可以用以下两种正则方案提取完整标题:
    1. 若标题在字符串末尾,匹配title:之后的所有内容:
      import re
      s = "{id:dac62466,title:How do I refer my friends?}"
      result = re.search(r'title:(.*)', s).group(1)
      print(result)  # 输出: How do I refer my friends?
      
      .*会匹配任意字符(除换行符)直到字符串结尾,刚好适配当前场景。
    2. 若字符串后续还有其他内容(比如{id:dac62466,title:How do I refer my friends?,status:active}),匹配到下一个逗号之前的内容:
      import re
      s = "{id:dac62466,title:How do I refer my friends?,status:active}"
      result = re.search(r'title:([^,]+)', s).group(1)
      print(result)  # 输出: How do I refer my friends?
      
      [^,]+表示匹配除逗号外的所有字符,能精准定位标题部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:17:35