Can I use a boolean AND condition in a regular expression?

ahmd0 picture ahmd0 · May 31, 2012 · Viewed 10.7k times · Source

Say, if I have a DN string, something like this:

OU=Karen,OU=Office,OU=admin,DC=corp,DC=Fabrikam,DC=COM

How to make a regular expression to pick only DNs that have both OU=Karen and OU=admin?

Answer

Eugene Ryabtsev picture Eugene Ryabtsev · May 31, 2012

This is the regex lookahead solution, matching the whole string if it contains required parts in any order just for the reference. If you do not store the pattern in some sort of configurable variable, I'd stick with nhahtdh's solution, though.

/^(?=.*OU=Karen)(?=.*OU=admin).*$/

^        - line start
(?=      - start zero-width positive lookahead
.*       - anything or nothing
OU=Karen - literal
)        - end zero-width positive lookahead
         - place as many positive or negative look-aheads as required
.*       - the whole line
$        - line end