边界超出匹配范围的正则表达式

问题描述 投票:0回答:1

我想匹配一个单词,但我希望捕获组包含匹配单词之前和之后的数字之间的所有内容。

在下面的示例中,匹配将是关键字,但会捕获“然后是一些文本关键字和更多数字”

       numbers 1, 2, 3 then some text KEYWORD and more numbers 1, 2, 3

regex regex-group
1个回答
0
投票

您可以使用以下正则表达式:

(?<=\d\s)((?:(?!\d).)*?KEYWORD(?:(?!\d).)*?)(?=\s\d)

我在 javascript 中使用了它并得到了输出。这是结果:

x = "numbers 1, 2, 3 then some text KEYWORD and more numbers 1, 2, 3";

result = x.match(/(?<=\d\s)((?:(?!\d).)*?KEYWORD(?:(?!\d).)*?)(?=\s\d)/)

result
如下:

[
    "then some text KEYWORD and more numbers",
    "then some text KEYWORD and more numbers"
]

我使用评论进行了更新。

© www.soinside.com 2019 - 2024. All rights reserved.