[英]Regex to match multiple occurances IFF another string occurs
I'm really hoping this can be solved in regex, but I fear not.... 我真的希望这可以在正则表达式中解决,但我不担心....
I'm looking for a regex that will return multiple matches of a term ONLY is another term appears in the same string. 我正在寻找一个正则表达式,只返回一个术语的多个匹配项是另一个术语出现在同一个字符串中。 This is better explained with an example.
用一个例子可以更好地解释这一点。 Consider:
考虑:
The numbers are 144, 424, and 345. Not 45.
I'd like to match '144', '424' and '345' only. 我想只匹配'144','424'和'345'。 (Any 3 digit number) - but only if they follow the term ' numbers ' somewhere before.
(任何3位数字) - 但前提是他们在某处遵循“ 数字 ”一词。 So the following aditional example:
以下是附加示例:
The numbers we are looking for: 234 & 992
Should return '234' and '992' only. 应该只返回'234'和'992'。
The following sentence should not match anything: 以下句子不应该匹配任何东西:
Some examples: 234, 244 and 12
I thought I was onto something with the following regex: 我以为我正在使用以下正则表达式:
(?<=numbers\b)(?:.|\n)*?\b(\d{3})\b
But it only matches the first number. 但它只匹配第一个数字。 Is what I'm trying to achieve even possible?
我正在努力实现的目标是什么? No manner of lookahead or lookbehind seems to work here.
没有前瞻或外观的方式似乎在这里工作。 For verious reasons I'm limited to this only being a single regex expression, and I don't have the option to selectivly access individual capturing groups after the fact.
出于各种原因,我仅限于这个只有一个正则表达式,并且我没有选择在事后选择性地访问各个捕获组。 So looking for a purely regex method!
所以寻找纯正的正则表达式方法!
You may use this regex with \\G
: 您可以将此正则表达式用于
\\G
:
(?:\bnumbers\b|(?!^)\G).*?\b(\d{3})\b
\\G
asserts position at the end of the previous match or the start of the string for the first match. \\G
在上一场比赛结束或第一场比赛的字符串开头处断言位置。 (?!^)
avoids matching \\G
at line start (?!^)
避免在行开始时匹配\\G
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.