Reputation: 1287
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.
Upvotes: 0
Views: 82
Reputation: 5048
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.
Upvotes: 1
Reputation: 26157
If you need any combination of foo
and bar
, then something like this would be enough:
^(foo|bar)+$
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*)+$
Upvotes: 1