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

Regular Expression to validate that there is a AND/OR between every word/double quote

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 and there can be spaces inside of the quotes. Also, the end of the string cannot be OR/AND.

For Example:

dog OR cat AND dog = true
dog cat = false
"Dog bot" 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 have this expression but it does not account for the double quote scenario:

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

^\S+(?: (?:OR|AND|") \S+)*$

>Solution :

You can use

^(?:"[^"]*"|\S+)(?: (?:OR|AND) (?:"[^"]*"|\S+))*$

See the regex demo.

Details:

  • ^ – start of string
  • (?:"[^"]*"|\S+)", zero or more chars other than " and then a ", or one or more non-whitespace chars
  • (?: (?:OR|AND) (?:"[^"]*"|\S+))* – zero or more sequences of
    • (?:OR|AND) – space + OR or AND + space
    • (?:"[^"]*"|\S+)", zero or more chars other than " and then a ", or one or more non-whitespace chars.
  • $ – end of string
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