【问题标题】:python regular expression: how to ignore the irrelevant matches?python正则表达式:如何忽略不相关的匹配?
【发布时间】:2021-07-29 21:34:45
【问题描述】:

我有一段文字,其中有一个句子包含“自从”一词。我的尝试是使用正则表达式来提取单词“since”之后的文本,直到下一个和上一个时期。比如文字是:

text = "I like to live in a big city. Today is Monday, since yesterday was Sunday."

我的正则表达式是

rule = re.compile(r'([a-zA-Z0-9\,\.\s\'])\bsince\b([a-zA-Z0-9\,\.\s\'])', re.IGNORECASE)
patterns = rule.match(text)

但是,patterns.group(1) 返回的I like to live in a big city. Today is Monday, 包含我不想要的句子,即我只想要Today is Monday, 。如何使用正则表达式来做到这一点?

【问题讨论】:

  • 如果你需要since之后直到下一个.,使用since\s*([^.]*)\bsince\b\s*([^.]*)
  • 使用r'[^.]*? since [^.]*?\.'

标签: python regex re


【解决方案1】:

您可以使用regex(?<=\.).*(?=\bsince\b)

  • (?<=\.):正向Lookbehind 断言.
  • .*: 任意字符任意次数
  • (?=\bsince\b):这个词的正向前瞻断言,since

演示:

import re

text = "I like to live in a big city. Today is Monday, since yesterday was Sunday."

m = re.search('(?<=\\.).*(?=\\bsince\\b)', text)
if m:
    print(m.group())

输出:

 Today is Monday, 

【讨论】:

    【解决方案2】:

    使用re.complie:在此处修复 OP 的尝试。

    import re
    rule = re.compile(r'.*?\.\s+([^,]*),\s+since', re.IGNORECASE)
    patterns = rule.match(text)
    patterns.group(1)
    'Today is Monday'
    


    使用您展示的示例,请尝试以下操作。我们可以在这里使用 Python 的 findall 函数 re 库。

    import re
    text = "I like to live in a big city. Today is Monday, since yesterday was Sunday."
    re.findall(r'.*?\.\s+([^,]*),\s+since',text)
    

    正则表达式的解释:

    .*?\.\s+([^,]*),\s+since:使用非贪婪匹配直到文字 . 然后提到 1 个或多个空格出现,然后是 Today 直到逗号出现(在捕获组中)。后跟 , 后跟空格 1 次或多次出现以及从此处开始的字符串。

    【讨论】:

      【解决方案3】:

      你可以使用这个正则表达式:

      [^.]*? since [^.]*?\.
      

      RegEx Demo

      代码:

      import re
      
      text = "I like to live in a big city. Today is Monday, since yesterday was Sunday."
      print (re.findall(r'[^.]*? since [^.]*?\.', text))
      

      输出:

      [' Today is Monday, since yesterday was Sunday.']
      

      正则表达式详细信息:

      • [^.]*?: 匹配 0 个或多个不是点的字符
      • since:匹配" since "
      • [^.]*?:匹配0个或多个不是点的字符
      • \.:匹配一个点

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2015-11-11
        • 2014-04-17
        • 1970-01-01
        • 2018-11-23
        • 2021-10-08
        相关资源
        最近更新 更多