【问题标题】:Match smallest possible sentence匹配最小可能的句子
【发布时间】:2021-07-25 21:04:23
【问题描述】:

文字:

One sentence here, much wow. Another one here. This is O.N.E. example n. 1, a nice one to understand. Hope it's clear now!

正则表达式:(?<=\.\s)[A-Z].+?nice one.+?\.(?=\s[A-Z])

结果:Another one here. This is O.N.E. example n. 1, a nice one to understand.

如何获取This is O.N.E. example among n. 1, a nice one to understand.? (即与正则表达式匹配的最小可能句子)

【问题讨论】:

    标签: python regex re findall


    【解决方案1】:

    只需在表达式前面插入一个贪婪的.*

    .*\.\s([A-Z].+?nice one.+?\.(?=\s[A-Z]))
    

    【讨论】:

    【解决方案2】:

    这里有一点不同的方法,只是拆分整个文本,然后过滤掉你想要的:

    import re
    s = "One sentence here, much wow. Another one here. This is O.N.E. example n. 1, a nice one to understand. Hope it's clear now!"
    result = [x for x in re.split(r'(?<=\B.\.)\s*',s) if 'nice one' in x][0]
    print(result) # This is O.N.E. example n. 1, a nice one to understand.
    

    不确定您有多少个边缘案例,但在这里我使用了 re.split() 和以下模式:(?&lt;=\B.\.)\s*。这意味着:

    • (?&lt;=\B.\.) - 断言位置的积极回溯是在 \b(单词边界)不适用的位置之后,后跟文字点。
    • \s* - 0+ 个空白字符。

    使用生成的数组,检查哪个元素包含您想要的单词“nice one”不会有太大问题。

    在线查看demo

    【讨论】:

      【解决方案3】:

      您可以排除匹配点,并且仅匹配大写字符后跟点或点后跟空格和数字的点。

      (?:(?<=\.\s)|^)[A-Z][^.A-Z]*(?:(?:[A-Z]\.|\.\s\d)[^.A-Z]*)*\bnice one\b.+?(?=\s[A-Z])
      
      • (?:(?&lt;=\.\s)|^) 断言 . 和左侧或字符串开头的空白字符
      • [A-Z][^.A-Z]* 匹配大写字符 A-Z 和除点或大写字符外的任何字符的 0+ 倍
      • (?:非捕获组
        • (?:[A-Z]\.|\.\s\d) 匹配 A-Z 和 . 或匹配 . 空格字符和数字
        • [^.A-Z]* 可以选择匹配除. 或大写字符以外的任何字符
      • )* 关闭群组并可选择重复
      • \bnice one\b.+?(?=\s[A-Z]) 匹配 nice one 并匹配直到在右侧断言一个 whitspace 字符和大写字符

      Regex demo

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-31
      • 2010-12-27
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      相关资源
      最近更新 更多