zubug55
zubug55

Reputation: 729

Regex to check words in string are separated only by spaces and not by _AND_/_OR_ python

Regex in python to check if words in string are not separated by words like _AND_,_OR_ and only separated by spaces.

meaning of underscore here is space after and before word AND/OR.

For eg:

1.) foo AND bar - should fail

2.) foo AND bar cafe - should fail because it has _AND_

3.) foo AND bar OR cafe foobar baz - fail because it has _AND_/_OR_ in it

4.) foo bar baz foobar - pass because it is separated only spaces and no _AND_/_OR_

5.) fooANDbarOR bar - pass because it is not separated by _AND_/_OR_.

I know how to check if words are separated by _AND_/_OR_ ->

\W(:?AND|OR)\W

I know how to check if words are separated by spaces ->

\w\s

But i don't know how to combine both these things such that strings are separated only by spaces and not by _AND_/_OR_

Upvotes: 0

Views: 478

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

You can use

^(?:[\w ](?! (AND|OR) ))+$

The repeated [\w ] ensures that all characters are either word characters or spaces, nothing else. After each character, negative lookahead for (AND|OR) to ensure that neither of those are standalone words:

https://regex101.com/r/LyRr5U/2

If you also want to exclude standalone words, add positive lookahead to the beginning of the regex to ensure that there are some word characters separated by spaces somewhere in the string:

^(?=.*\w +\w)(?:[\w ](?! (AND|OR) ))+$

Upvotes: 1

Related Questions