0

I need a regex that would match the following example strings:

 Example 1: "red, blue, and hot"
 Example 2: "red, blue, or hot"

Three individual words, the first two followed by commas, and the conjunction 'and' (case 1) alternatively 'or' (case 2).

Case 1: "<word01>, <word02>, and <word03>"
Case 2: "<word01>, <word02>, or <word03>"

I have the following regex (\w+,(\s|\n)+){2}(and|or) that successfully matches the strings however it will also match strings where my example expressions are contained within the string. I only want a successful match if the string contains my example expression and nothing else.

In other words green, red, blue, and hot should not match as it contains an additional word and comma before the match.

1 Answers1

0

REGEX Variations

I gave you a few variations depending how you want to deal with punctuation.

RegEx ➡ (^\w+\,\s+\w+\,\s+(and|or)\s+\w+\Z)                               
Match Test String
red, blue, and hot
red, blue, and hot.
green, red, blue, and hot
red, blue, and hot, but not green

 

RegEx ➡ (^\w+\,\s+\w+\,\s+(and|or)\s+\w+\.\Z)                         
Match Test String
red, blue, and hot
red, blue, and hot.
green, red, blue, and hot
red, blue, and hot, but not green

 

RegEx ➡ (^\w+\,\s+\w+\,\s+(and|or)\s+\w+\.?\Z)                         
Match Test String
red, blue, and hot
red, blue, and hot.
green, red, blue, and hot
red, blue, and hot, but not green

 

REGEX Used

Regex Description                                                                          
    ^ start of the string (position)
    \Z end of the string (position)
    + previous token > 0 times
    ? previous token < 2 times
    \w any single word character
    \, comma character
    \s whitespace character
    | separates alternatives (or)
    \. period character