【问题标题】:RegEx for capturing part of a string用于捕获部分字符串的正则表达式
【发布时间】:2019-10-12 02:00:37
【问题描述】:

我正在尝试使用 Python 的 re 库在 .md 文档中获取顶级 Markdown 标题(即,以单个哈希开头的标题 -- # Introduction),但我一生都无法弄清楚这一点。

这是我要执行的代码:

import re

pattern = r"(# .+?\\n)"

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

header = re.search(pattern, text)
print(header.string)

print(header.string) 的结果是:

# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n 而我只想要# Title\n

这个关于 regex101 的例子说它应该可以工作,但我不知道为什么不能。 https://regex101.com/r/u4ZIE0/9

【问题讨论】:

    标签: python regex markdown regex-lookarounds regex-group


    【解决方案1】:

    我猜我们希望提取# Title\n,在这种情况下,您的表达式似乎可以正常工作,只需稍作修改:

    (# .+?\\n)(.+)
    

    DEMO

    测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r"(# .+?\\n)(.+)"
    
    test_str = "# Title\\n## Chapter\\n### sub-chapter#### The Bar\\nIt was a fall day.\\n"
    
    subst = "\\1"
    
    # You can manually specify the number of replacements by changing the 4th argument
    result = re.sub(regex, subst, test_str, 1)
    
    if result:
        print (result)
    
    # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
    

    【讨论】:

      【解决方案2】:

      你得到这个结果是因为你使用了header.string,它在Match object上调用.string,这将返回传递给match()或search()的字符串。

      字符串中已经有换行符:

      text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
      

      因此,如果您使用您的模式(请注意,它也会匹配换行符),您可以将代码更新为:

      import re
      
      pattern = r"(# .+?\\n)"
      text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
      header = re.search(pattern, text)
      print(header.group())
      

      Python demo

      请注意,re.search 会查找正则表达式生成匹配项的第一个位置。

      匹配您的值的另一个选项可能是从字符串的开头匹配 #,后跟一个空格,然后是除换行符之外的任何字符,直到字符串的结尾:

      ^# .*$
      

      例如:

      import re
      
      pattern = r"^# .*$"
      text = "# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
      header = re.search(pattern, text, re.M)
      print(header.group())
      

      Python demo

      如果后面不能有#,您也可以使用negated character class 来匹配# 或换行符:

      ^# [^#\n\r]+$
      

      【讨论】:

      • 呃——就是这样!如果我刚刚完成print(header),我会看到它匹配正确。谢谢!
      猜你喜欢
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 2022-01-12
      • 2019-10-10
      相关资源
      最近更新 更多