将字符串限制为最短匹配与最长匹配(非贪婪组)的正则表达式?

Regular Expression to limit a string to the shortest match versus the longest match (non-greedy group)?

我正在文本段落内搜索。

我想在那些以特定词开头的段落中找到字符串,然后抓取紧跟在该匹配词之后的文本。我想在遇到第一个句点、感叹号、问号或换行符时停止...如果在搜索词的 100 个字符内找到其中 none 个,我想剪切字符串在最接近 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'

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

使用否定字符 class 排除点!

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