tags:

views:

34

answers:

3

Hi there,

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.

Thanks in advance!

+1  A: 

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

Bolo
+1  A: 

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
+1  A: 

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

\b(roster|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 roster or a hen."
  • not match in "Chickens are either a rosters or hens." - but (roster|hen) would

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

Tomalak