ThiefMaster
ThiefMaster

Reputation: 318698

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 matching 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.

Upvotes: 4

Views: 1608

Answers (1)

Jens
Jens

Reputation: 25593

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

Upvotes: 6

Related Questions