What does the ?! mean in the following regex expression?
new RegExp('http:\/\/(?!' + location.hostname + ')')
Best Answer
It's a negative lookahead, which means that for the expression to match, the part within (?!...)must not match. In this case the regex matches http://only when it is not followed by the current host name (roughly, see Thilo's comment).
(?!regex) is a zero-width negative lookahead. It will test the characters at the current cursor position and forward, testing that they do NOT match the supplied regex, and then return the cursor back to where it started.
The whole regexp:
/
FTW # Match Characters 'FTW'
( # Start Match Group 1
( # Start Match Group 2
(?!FTW|ODP) # Ensure next characters are NOT 'FTW' or 'ODP', without matching
. # Match one character
)+ # End Match Group 2, Match One or More times
) # End Match Group 1
OD # Match characters 'OD'
P+ # Match 'P' One or More times
/
So - Hunt for FTW, then capture while looking for ODP+ to end our string. Also ensure that the data between FTW and ODP+ doesn't contain FTW or ODP
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured.
Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
Best Answer
It's a negative lookahead, which means that for the expression to match, the part within
(?!...)
must not match. In this case the regex matcheshttp://
only when it is not followed by the current host name (roughly, see Thilo's comment).