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

Time:11-02

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:

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

CodePudding user response:

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
  • Related