Regex to match if a following named group matches

^(?<foo>[a-z]+)?(?<bar>[1-9]+)?$

I need to match a whitespace if bar, which is optional, is present/match. If bar is not a match, no whitespace is needed.

abc 100 is a match

abc is a match

abc_ is not a match (underscore = whitespace)

abc100 is not a match

EDIT: Sorry, I totally missed an additional requirement.

100 is also a match. foo is optional, so if foo is not present, but bar is, then there should be no leading whitespace.

Can you advise what I need to do?

Read more here: Source link