0
votes

How would I construct a regex that would match if either "foo" and "bar" (or any combination thereof) where present but NOTHING ELSE was?

So for example:

"foo bar ipsum dolor sit amet, consectetur adipiscing elit" - NO MATCH

"ipsum dolor sit amet, consectetur adipiscing elit foo" - NO MATCH

"foo ipsum dolor sit amet, bar consectetur adipiscing elit foo" - NO MATCH

"foo" - MATCH

"bar" - MATCH

"barfoo" - MATCH

"foobarbarfoofoobar" - MATCH

I'm trying to grok negative lookaheads but I haven't been able to crack this yet.

3
should "foo bar" or "bar, foo" match? - DRC
Is foofoofoo a valid match? - anubhava
@DRC - First one yes, second one no. - TheNovice
@anubhava - yes - TheNovice

3 Answers

1
votes

If you need any combination of foo and bar, then something like this would be enough:

^(foo|bar)+$

Live preview

It will capture foo, bar, foobar, barfoofoo and even foobarbarfoofoobar, etc.

Edit:

Since you also want to match foo bar, you'd have to include \h. Remember that \h matches spaces and tabs, while \s also matches new lines.

^((?:foo|bar)\h*)+$

Live preview

1
votes

You can use this regex:

^\h*(?:(?:foo|bar)\h*)+$

RegEx Demo

1
votes

If you need to match also spaces characters you could use something like

^(foo|bar)+(foo|bar|\s)*$

this is a naive solution given ones showing capturing groups are already showed as answers.