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?
-
4In what language/environment is this regex being implemented? Regex seems like unnecessary overhead in many situations.– mickmackusaJun 1, 2019 at 9:31
Add a comment
|
2 Answers
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
-
60For 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
). Dec 18, 2013 at 15:45 -
1Hi quick question, what should I do if I do not want applebanana to match? Mar 31, 2020 at 16:55
-
1The regex above matches apple and banana, but does not match applebanana. Mar 31, 2020 at 16:58
-
1Do not confuse round brackets that are used here with square brackets for a character class.– TimoJul 20, 2022 at 18:16
-
There are different regex engines but I think most of them will work with this:
apple|banana
-
67If you plan to put more in your regex, you'll need to put parentheses around your words, like this:
(apple|banana)
.– Brian JOct 14, 2014 at 13:01 -
3
-
That's set with the
re.IGNORECASE
flag. E.g.:re.compile("(apple|banana)", re.IGNORECASE)
Jan 31, 2020 at 9:42