开发者

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?://.+(?<!/)$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜