Regex To Match A String That Contains One Word Or Another

A Regular Expression that matches a string containing one word or another.

/([0-9]+)\s+((\bdogs\b)|(\bcats\b))/

Explain:

  • 0-9 Range. Matches a character in the range “0” to “9” (char code 48 to 57). Case sensitive.
  • + Quantifier. Match 1 or more of the preceding token.
  • \s Whitespace. Matches any whitespace character (spaces, tabs, line breaks).
  • + Quantifier. Match 1 or more of the preceding token.
  • \b Word boundary. Matches a word boundary position between a word character and non-word character or position (start / end of string).
  • | Alternation. Acts like a boolean OR. Matches the expression before or after the |.

Matches:

  • I have 5 dogs and 3 cats.

Non-matches:

  • I have 5dogs and 3cats.