462

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?

1
  • 4
    In what language/environment is this regex being implemented? Regex seems like unnecessary overhead in many situations. Jun 1, 2019 at 9:31

2 Answers 2

712

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
5
  • 60
    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, 2013 at 15:45
  • 1
    Hi quick question, what should I do if I do not want applebanana to match?
    – Sean Reyes
    Mar 31, 2020 at 16:55
  • 1
    The regex above matches apple and banana, but does not match applebanana.
    – phlogratos
    Mar 31, 2020 at 16:58
  • 1
    Do not confuse round brackets that are used here with square brackets for a character class.
    – Timo
    Jul 20, 2022 at 18:16
  • What does captured strings mean?
    – Pathros
    Aug 19, 2022 at 15:33
139

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

apple|banana
3
  • 67
    If you plan to put more in your regex, you'll need to put parentheses around your words, like this: (apple|banana).
    – Brian J
    Oct 14, 2014 at 13:01
  • 3
    but how to make it case insensitive?
    – Nitish
    Jan 23, 2020 at 17:24
  • That's set with the re.IGNORECASE flag. E.g.: re.compile("(apple|banana)", re.IGNORECASE) Jan 31, 2020 at 9:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.