Regex match when substring present

Viewed 41

I would like to use regex to match numbers if a substring is present, but without matching the substring. Hence,

2-4 foo
foo 4-6
bar 8

should match

2, 4
4, 6

I currently have

(\d{0,}\.?\d{1,})

which returns the numbers (int or float). Using

(\d{0,}\.?\d{1,}(?=\sfoo))

only matches 4, rather than 2 and 4. I also tried a lookahead

^(?=.*?\bfoo\b)(\d{0,}\.?\d{1,})

but that matches the 2 only.

*edited typo

1 Answers

With engines that support infinite width lookbehind patterns, you can use

(?<=\bfoo\b.*)\d*\.?\d+|\d*\.?\d+(?=.*?\bfoo\b)

See this regex demo. It matches any zero or more digits followed with an optional dot and then one or more digits when either preceded with a whole word foo (not necessarily immediately) or when followed with foo whole word somewhere to the right.

When you have access to the code, you can simply check for the word presence in the text and then extract all the match occurrences. In Python, you could use

if 'foo' in text:
    print(re.findall(r'\d*\.?\d+', text))
# Or, if you need to make sure the foo is a whole word:
if re.search(r'\bfoo\b', text):
    print(re.findall(r'\d*\.?\d+', text))
Related