18

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
UpHelix
  • 4,666
  • 10
  • 54
  • 82

3 Answers3

20

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)
Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
  • I'm only given an input field to put this regex in, its for google analytics. They show their example of just a simple /yourregex/. Would you guess that lookahead will work? I don't know what programming language they will use to run the regex. – UpHelix Mar 24 '11 at 16:08
  • Looks like GA (Google Analytics) supports lookahead. http://www.lunametrics.com/blog/2007/08/08/regular-expressions-for-ga-bonus-iii-lookahead/ – UpHelix Mar 24 '11 at 16:14
  • is there a workaround for languages like go which does not support lookahead? – klew Jul 24 '20 at 11:15
  • @klew: You would need to hard-code all the possible permutations, so for a regex that checks if `a`, `b`, and `c` are present in any order, you'd need to search for `a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a`. – Tim Pietzcker Jul 24 '20 at 11:19
  • This of course is error-prone and scales horribly, so it's probably better to do three separate regex calls, one for each criterion, and make sure that all three match. – Tim Pietzcker Jul 24 '20 at 11:30
4
^(?=.*?p=completed)(?=.*?advancebrain)(?=.*?com_ixxocart).*$

Spent too long testing and refining =/ Oh well.. Will still post my answer

Richard Parnaby-King
  • 13,858
  • 11
  • 64
  • 123
1

Use lookahead:

(?=.*\badvancebrain)(?=.*\bcom_ixxocart)(?=.*\bp=completed)

Order won't matter. All three are required.

Tom
  • 41
  • 2