Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
CyberJunkie Avatar asked Jul 28 '11 18:07

CyberJunkie


People also ask

How do you match a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do you regex multiple words?

However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.

What is a word boundary regex?

A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ( [0-9A-Za-z_] ).


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 
like image 165
phlogratos Avatar answered Sep 23 '22 05:09

phlogratos


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

apple|banana 
like image 40
smoak Avatar answered Sep 23 '22 05:09

smoak