代码之家  ›  专栏  ›  技术社区  ›  user3649739

正则表达式仅在句子中查找模式[重复]

  •  -1
  • user3649739  · 技术社区  · 6 年前

    我试图提取一个有两个单词/术语的模式,但只有当它们出现在句子中时,在这个测试用例中既有“模式”也有“句子”。所以:

    Find the pattern when it is. In the same sentence. Find the pattern when it is in the same sentence.
    

    应该只在最后一句找到匹配项。

    正如你在我的Regex101测试中看到的, (?P<Capture>pattern.*?sentence).*?\. 无论如何都能找到它:

    https://regex101.com/r/xDIU5q/2

    据我所知,我已经要求正则表达式在找到句点之前不要贪婪地匹配。但这似乎并没有限制它这样做。

    1 回复  |  直到 6 年前
        1
  •  0
  •   aaaa    6 年前

    https://regex101.com/r/V1aGaY/4

    图案: ((?<=\s)[^.]+(pattern)[^.]+(sentence)(?=\.)|(?<=\s)[^.]+(sentence)[^.]+(pattern)(?=\.))

    测试字符串: Find the pattern when it is. In the same sentence. Find the pattern when it is in the same sentence. Find the sentence when it is in the same pattern.

    我相信,这应该能满足你的需求。这假设句子由空格分隔,空格可以很容易地修改,只需LMK即可。