Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex Expression to validate that the words "OR" and "AND" follow every other word

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 +.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading