Search code examples
regexboolean-operations

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


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?


Solution

  • 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