I am trying to create a regular expression that only matches when a string consists of instances of some pattern. Let's say that I only need a string to consist of "foo" or "bar" substrings separated by a space.
So, valid instances are: "foo", "bar", "foo foo", "foo bar", "foo foo bar", "foo bar foo bar"... Invalid instances: "foofoo bar", "baz foo bar", "foo bar baz"
Thus, each instance of foo or bar (i.e. my base pattern or capture group), should be preceded by either a space or be at the start of string, and it should be ended either with a space, or be located at the end of the string.
It seemed like a simple task, but I can't figure it out.
This is what I got so far:
(?:^|bar\s|foo\s)(foo|bar)(?=$|\sbar|\sfoo)
It doesn't work on "foofoo bar" (somehow it's valid).
I'm testing it in Python. But it would be good if it worked in JS too.