开发者

Why doesn't this regex reject trailing slashes (using negative lookahead)?

开发者 https://www.devze.com 2023-03-07 18:49 出处:网络
I\'m using the following regex (PCRE) to (very basically) validate an URL to start with http[s]:// and reject trailing slashes: ^https?://.+(?!/)$

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

精彩评论

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

关注公众号