TheNovice
TheNovice

Reputation: 1287

Regex match if a couple options found but literally nothing else is

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

Answers (3)

DRC
DRC

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

vallentin
vallentin

Reputation: 26157

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

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You can use this regex:

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

RegEx Demo

Upvotes: 1

Related Questions