回顾先行断言中的模式

3
我的问题涉及到“lookbehinds”,我想找到单词“this”后面的所有第一个数字,我有以下数据:
188282 this is an example of a number 12345 and 54321 188282 this is an example of a number 1234556 this is an example of a number 1234556 187293 this is another example of a number 74893 and 83978
模式:
this is an example of a number \d+
输出:
188282 this is an example of a number 12345 and 54321 188282 this is an example of a number 1234556 this is an example of a number 1234556 187293 this is another example of a number 74893 and 83978
为了匹配它们,我使用了更通用的方法,因为我知道我想要在单词“this”后面的第一个数字
模式:
this[^\d]+\d+
输出:
188282 this is an example of a number 12345 and 54321 188282 this is an example of a number 1234556 this is an example of a number 1234556 187293 this is another example of a number 74893 and 83978
现在我尝试使用lookbehind,因为我不想在结果中包含模式的一部分。按照我的第一种方法:
模式:
(?<=this is an example of a number )\d+
输出:
188282 this is an example of a number 12345 and 54321 188282 this is an example of a number 1234556 this is an example of a number1234556 187293 this is another example of a number 74893 and 83978
看起来我正在接近目标,我想像之前一样覆盖最后一种情况,所以我尝试了我的第二种方法。
模式:
(?<=this[^\d]+)\d+
输出:
188282 this is an example of a number 12345 and 54321 188282 this is an example of a number 1234556 this is an example of a number 1234556 187293 this is another example of a number 74893 and 83978

没有匹配的内容
在回顾后面是否可能有模式?我是不是对这个问题采取了错误的方法?这有点长,但我想向您展示我迄今为止尝试过的东西,而不是仅仅问问题

提前感谢

3个回答

2

是的,您可以在后顾式中使用模式,但是在大多数正则表达式中不允许使用变长后顾式。换句话说,在后顾式中不能使用量词(但是允许使用固定量词,如 {n})。但是某些正则表达式允许您使用选择分支符 | 或有限制的量词(例如 Java 中的 {1,n})。

在 .net 语言中,允许使用变长后顾式。


此答案已添加到Stack Overflow正则表达式FAQ,位于“环视”一节下。 - aliteralmind
@aliteralmind:很酷,我会尽快改进它。(我目前正在编辑几篇有同样错误的帖子) - Casimir et Hippolyte
期待着。 - aliteralmind
自 Perl 5.30 起,这在实验中是被允许的:https://perldoc.pl/perl5300delta#Limited-variable-length-lookbehind-in-regular-expression-pattern-matching-is-now-experimentally-supported - Grinnz

1

关于回顾前瞻,有一点需要注意的是,并非所有语言都支持变宽度的回顾前瞻(不能支持其中内容为可变数量字符的回顾前瞻)。

可以采用的方法是使用前瞻和捕获组:

(?=this[^\d]+(\d+))

regex101演示

或者使用\K正则表达式字符,它可以重置匹配(如果您的正则表达式引擎支持它)。

this[^\d]+\K\d+

regex101演示


感谢提供其他的解决方案。 - Joao Raposo
有趣的是,.Net不支持\K(你在提到它支持的情况下),但它支持可变宽度回顾。 - Joao Raposo
@JoaoRaposo 是的!那是真的。想想为什么有些语言实现了某些东西而其他语言则没有!JavaScript也不支持!如果你的语言/正则表达式引擎都不支持(可能很少见,但谁知道呢),我建议简单地使用this[^\d]+(\d+),并只取第一个捕获组(忽略主要捕获)。 - Jerry
我是一名 .net 开发者,所以我想我在这个问题上应该没问题,但我肯定会看一下差异,说实话我之前并不知道这个问题。再次感谢您的建议。 - Joao Raposo

0

这取决于你的正则表达式实现。你需要进行一些测试。

我知道有些实现不喜欢这样写:

(?<=\d{1,5})(?<=\w*)

但是它们可以很好地处理这个:

(?<=\d{5})(?<=\w{1000})

换句话说,没有重复或灵活长度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接