Reputation: 1700
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. (Any 3 digit number) - but only if they follow the term 'numbers' somewhere before. So the following aditional example:
The numbers we are looking for: 234 & 992
Should return '234' and '992' only.
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!
Upvotes: 6
Views: 99
Reputation: 785991
You may use this regex with \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.(?!^)
avoids matching \G
at line startUpvotes: 3