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?
Asked
Active
Viewed 5e+01k times
490

CyberJunkie
- 21,596
- 59
- 148
- 215
-
4In what language/environment is this regex being implemented? Regex seems like unnecessary overhead in many situations. – mickmackusa Jun 01 '19 at 09:31
2 Answers
745
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
- 607,720
- 39
- 448
- 563

phlogratos
- 13,234
- 1
- 32
- 37
-
62For 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
-
1Hi quick question, what should I do if I do not want applebanana to match? – Sean Reyes Mar 31 '20 at 16:55
-
1The regex above matches apple and banana, but does not match applebanana. – phlogratos Mar 31 '20 at 16:58
-
1Do not confuse round brackets that are used here with square brackets for a character class. – Timo Jul 20 '22 at 18:16
-
-
When used with grep in a bash shell, you should escape the `|` example: `cat file | grep 'apple\|banana'` – Eden Apr 27 '23 at 06:25
139
There are different regex engines but I think most of them will work with this:
apple|banana

smoak
- 14,554
- 6
- 33
- 33
-
70If 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 '14 at 13:01
-
3
-
That's set with the `re.IGNORECASE` flag. E.g.: `re.compile("(apple|banana)", re.IGNORECASE)` – Troels Ynddal Jan 31 '20 at 09:42