2

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

8
  • but that matches the 4 only. No it should match the 2 only. Commented May 20, 2021 at 11:22
  • shouldn't \.? be \-? (or -? since not in []) or just .?? Commented May 20, 2021 at 11:23
  • Sorry @iBug, yes you are absolutely correct. Commented May 20, 2021 at 11:24
  • 1
    You need to specify the regex flavor. Else, the suggested pattern might either be suboptimal or just won't work. See (?<=\bfoo\b.*)\d*\.?\d+|\d*\.?\d+(?=.*?\bfoo\b) demo. Commented May 20, 2021 at 11:26
  • This doesn't seem like a good application of regex. Better build the substring detection logic with other techniques available, then apply regex to extract numbers. Commented May 20, 2021 at 11:26

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.