Suppose one would like to match an arbitrary number, that is either preceded or followed by a certain string. However, if possible, the pattern should always prefer to match the substring where the number is followed by the string.
For example:
- the string
1234 fooshould match. - the string
foo 1234should match. - the string
1234 foo 1234should produce the match1234 foo. - (most important) the string
foo 1234 fooshould produce the match1234 fooand notfoo 1234.
To avoid having the same expression twice, only inverted and separated by an or, I've been trying to implement it using a conditional pattern. Using the pattern below works for the cases 1-3, but fails for case 4 as it matches foo 1234.
(\d+)?(?:(?(1) ?)(foo) ??)(?(1)|(?:(\d+)))
Adding a negative lookahead to the conditional like below also doesn't help. The string foo 1234 foo now produces the two matches foo 123 and 4 foo.
(\d+)?(?:(?(1) ?)(foo) ??)(?(1)|(?:(\d+)(?! ?foo)))
Since the regex is greedy it always matches the non-preferred substring in case 4 first. Is there a way to make the regex expression prefer the later match with a conditional expression?