34

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.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Pete
  • 343
  • 1
  • 3
  • 4

5 Answers5

71

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

ObiHill
  • 11,448
  • 20
  • 86
  • 135
Tomalak
  • 332,285
  • 67
  • 532
  • 628
4

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

Bolo
  • 11,542
  • 7
  • 41
  • 60
4

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)$

Gnana
  • 614
  • 1
  • 7
  • 18
2

You didn't mention what engine/language you're using, but in general, the regular expression would be (rooster|hen). | is the alternation operator.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
1

the thing that worked for me is

(?:word|anotheer word)

here an example of using I used it in my application http://regexr.com/3gjb2

if you are interested in understanding how (?: is diff from ( check this question

What does (?: do in a regular expression

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92