Professional Documents
Culture Documents
Regular Expressions
Regular Expressions
Regular Expressions
The OR version is fairly simple; as you said, it's mostly a matter of inserting pipes between
individual conditions. The regex simply stops looking for a match as soon as one of the
alternatives matches.
/^abc|xyz$|123|^(?:(?!456).)*$/
That fourth alternative may look bizarre, but that's how you express "doesn't contain" in a
regex. By the way, the order of the alternatives doesn't matter; this is effectively the same
regex:
/xyz$|^(?:(?!456).)*$|123|^abc/
The AND version is more complicated. After each individual regex matches, the match
position has to be reset to zero so the next regex has access to the whole input. That
means all of the conditions have to be expressed as lookaheads (technically, one of them
doesn't have to be a lookahead, I think it expresses the intent more clearly this way). A final
.*$ consummates the match.
/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/
And then there's the possibility of combined AND and OR conditions--that's where the real
fun starts. :D