Why doesn't this regex reject trailing slashes (using negative lookahead)?
I'm using the following regex (PCRE) to (very basically) validate an URL to start with http[s]:// and reject trailing slashes: ^https?://.+(?!/)$
However, the negative lookahead does not prevent the regex from ma开发者_开发问答tching an url with a trailing slash.
I know that I can simply use ^https?://.*[^/]$
but I'd like to know why the lookahead does not work.
Your lookahead checks if the last character of the string (the one before the end-of-line) is followed by a slash. It is not, since no character follows it, so the (?!/)
will never prevent a match.
You could use
^https?://.*(?!/).$
or
^https?://.+(?<!/)$
精彩评论