422

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?

CyberJunkie
  • 20,068
  • 55
  • 141
  • 210
  • 4
    In what language/environment is this regex being implemented? Regex seems like unnecessary overhead in many situations. – mickmackusa Jun 01 '19 at 09:31

2 Answers2

643

This will do:

/^(apple|banana)$/

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

(?:apple|banana)

Or, if you use a standalone pattern:

apple|banana
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
phlogratos
  • 12,089
  • 1
  • 30
  • 37
  • 54
    For some, using this as a non-capturing group will be useful. Using `(?:apple|banna)` will match either, but will not add them to the list of captured strings (eg `$1`, `$2`.. `$N`). – doub1ejack Dec 18 '13 at 15:45
  • 1
    Hi quick question, what should I do if I do not want applebanana to match? – Sean Reyes Mar 31 '20 at 16:55
  • The regex above matches apple and banana, but does not match applebanana. – phlogratos Mar 31 '20 at 16:58
129

There are different regex engines but I think most of them will work with this:

apple|banana
smoak
  • 13,836
  • 6
  • 31
  • 33