I am trying to create a Regex expression to validate that a string has the words "OR" and "AND" in between each word. The user can also have quotes around words so it needs to follow the quotes as well. Also, the end of the string cannot be OR/AND.
For Example:
dog OR cat AND dog = true
dog cat = false
"Dog" OR cat = true
Dog or cat and dog = false (OR/AND need to be capitalized)
cat OR dog AND "bob" = true
dog OR CAT OR = false
I am fairly new to Regex so any help is appreciated! Thank you!
>Solution :
You can match the first word, then match zero or more combination of AND/OR keywords + word.
^\S+(?: (?:OR|AND) \S+)*$
Regex Explanation:
^: start of string\S+: any non-space character(?: (?:OR|AND) \S+)+: "AND"/"OR" followed by non-space characters$: end of string
Check the demo here.
Note: if you want to force at least the presence of one AND/OR, then you need to change the final * with the +.