Regex AND operator

user366735 picture user366735 · Jun 15, 2010 · Viewed 223.7k times · Source

Based on this answer

Regular Expressions: Is there an AND operator?

I tried the following on http://regexpal.com/ but was unable to get it to work. What am missing? Does javascript not support it?

Regex: (?=foo)(?=baz)

String: foo,bar,baz

Answer

Mark Byers picture Mark Byers · Jun 15, 2010

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).