Regex match one of two words

CyberJunkie picture CyberJunkie · Jul 28, 2011 · Viewed 304.6k times · Source

I have an input that can have only 2 values apple or banana. What regular expression can I use to ensure that either of the two words was submitted?

Answer

phlogratos picture phlogratos · Jul 28, 2011

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)