ChatGPT解决这个技术问题 Extra ChatGPT

Regex match one of two words

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?

In what language/environment is this regex being implemented? Regex seems like unnecessary overhead in many situations.

W
Wiktor Stribiżew

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

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).
Hi quick question, what should I do if I do not want applebanana to match?
The regex above matches apple and banana, but does not match applebanana.
Do not confuse round brackets that are used here with square brackets for a character class.
s
smoak

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

apple|banana

If you plan to put more in your regex, you'll need to put parentheses around your words, like this: (apple|banana).
but how to make it case insensitive?
That's set with the re.IGNORECASE flag. E.g.: re.compile("(apple|banana)", re.IGNORECASE)