How to match multiple words in regex

UpHelix picture UpHelix · Mar 24, 2011 · Viewed 35k times · Source

Just a simple regex I don't know how to write.

The regex has to make sure a string matches all 3 words. I see how to make it match any of the 3:

/advancedbrain|com_ixxocart|p\=completed/

but I need to make sure that all 3 words are present in the string.

Here are the words

  1. advancebrain
  2. com_ixxocart
  3. p=completed

Answer

Tim Pietzcker picture Tim Pietzcker · Mar 24, 2011

Use lookahead assertions:

^(?=.*advancebrain)(?=.*com_ixxochart)(?=.*p=completed)

will match if all three terms are present.

You might want to add \b work boundaries around your search terms to ensure that they are matched as complete words and not substrings of other words (like advancebraindeath) if you need to avoid this:

^(?=.*\badvancebrain\b)(?=.*\bcom_ixxochart\b)(?=.*\bp=completed\b)