How to match character groups separated by spaces using RegEx?

How to match character groups separated by spaces using RegEx?



I use the below RegEx to indentify if some string is separated by either AND or OR


AND


OR


W(:?AND|OR)



Examples



Similarly, I want to write a regex which matches all the strings that are separated by only spaces and not by AND or OR.


AND


OR



I tried the below RegEx:


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



This gave the correct output on:



But an incorrect output on:



To Summarise: What is a way to check if a long string consists only of groups of characters separated just by spaces.



Example of a valid string:


foo1,3 acb[1-2] a foo bar bar(qwer|qwyr)



(Valid since there are spaces separating each block of characters)





Do you want to check if a string contains a space?
– Daniel Mesejo
Aug 28 at 1:32





just separated by spaces and not by words AND / OR (meaning of underscore is space) eg : foo AND bar is fine ; fooANDbar will not match W(:?AND|OR)W
– zubug55
Aug 28 at 1:37





Does fooANDbar spam matches?
– Daniel Mesejo
Aug 28 at 1:42






What, then, is your definition of a word? If you only want to check for spaces you can use str.split() and don't even need regex
– pkqxdd
Aug 28 at 2:19


word


str.split()




1 Answer
1



This solves my question:


k = "foo1,3 acb[1-2] AND a foo bar bar(qwer|qwyr)"
if not re.search(r'W(:?AND|OR)W', k) and k.strip().find(" ")!=-1:
print "not separated by AND and OR but by space"
else:
print "separated by AND/OR"






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.