Regex match one of two words

RegexFormsValidation

Regex Problem Overview


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?

Regex Solutions


Solution 1 - Regex

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

Solution 2 - Regex

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

apple|banana

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCyberJunkieView Question on Stackoverflow
Solution 1 - RegexphlogratosView Answer on Stackoverflow
Solution 2 - RegexsmoakView Answer on Stackoverflow