【问题标题】:Regular Expression to limit a string to the shortest match versus the longest match (non-greedy group)?正则表达式将字符串限制为最短匹配与最长匹配(非贪婪组)?
【发布时间】:2015-03-20 00:18:15
【问题描述】:

我正在文本段落中搜索。

我想在那些以特定单词开头的段落中查找字符串,然后抓取紧跟该匹配单词的文本。遇到第一个句号、感叹号、问号或换行符时我想停下来……如果在搜索词的 100 个字符内都找不到这些,我想在该词处截断字符串边界最接近 100 个字符的限制。

我该怎么做?

示例

string: "A test sentence containing an ngram and ending with a period. Another sentence that does not have the word we're searching for and runs on until we're past 100 characters."

regex: /\bngram(.{0,100})(\.|\b)/i

desired output: ' and ending with a period'

在这种情况下,我的正则表达式返回 " 并以句点结尾。另一个没有我们正在搜索并运行的单词的句子。"它持续的时间比我想要的要长,因为它的周期/单词边界捕获组是贪婪的(也许?)。我不知道如何限制较短的匹配,而不是最长的匹配。

【问题讨论】:

    标签: regex nlp extraction regex-greedy non-greedy


    【解决方案1】:

    使用排除点的否定字符类!

    /\bngram([^.]{0,100})(\b|\.)/i
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 2010-12-27
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多