Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression that checks for 2 specific words

Tags:

regex

I'm looking for a regular expression that checks whether a string contains 2 specific words.

e.g. Whether the string contains rooster or hen.

like image 250
Pete Avatar asked Aug 19 '10 18:08

Pete


People also ask

How do you search for multiple words in a regular expression?

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 ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .


3 Answers

The expresssion to match rooster or hen as a complete word (i.e. not when they are part of a longer, different word):

\b(rooster|hen)\b 

This is a safety measure to avoid false positives with partial matches.

The \b denotes a word boundary, which is the (zero-width) spot between a character in the range of "word characters" ([A-Za-z0-9_]) and any other character. In effect the above would:

  • match in "A chicken is either a rooster or a hen."
  • not match in "Chickens are either a roosters or hens." - but (rooster|hen) would

As a side note, to allow the plural, this would do: \b(roosters?|hens?)\b

like image 89
Tomalak Avatar answered Sep 22 '22 14:09

Tomalak


Use | for alternatives. In your case it's: (rooster|hen)

like image 33
Bolo Avatar answered Sep 18 '22 14:09

Bolo


I had a similar requirement but it should only contain a particular word (from a list) and no other words should be present in the string. I had to use ^(rooster|hen)$

like image 20
Gnana Avatar answered Sep 21 '22 14:09

Gnana