Alisa Liso
Alisa Liso

Reputation: 36

Match regex with no consecutive characters

I have this regex (link to the regexr.com with this pattern and examples)

const reg = /^(?:http(s)?:\/\/)[\w.-]+(?:\.[\w.-]+)+[/]?[\w\-._~:?#[\]@!$&'()*+,;=./]+$/gm

And it matches this urls

https://google.com
http://www.cool.com.au
http://www.cool.com.au/ersdfs
http://www.cool.com.au/ersdfs?dfd=dfgd@s=1
http://www.example.com
http://www.example.com/asdasd/asdasdasd
http://www.example.com/
http://www.example.com/////

And not matches this

http://www.cool.com:81/index.html asdasd
https:google.com
www.cool.com.au

Where can I add exception so it will not match urls like this http://www.example.com///// with consecutive / character?

I've tried to add /{1} and (?!./) but it's not working.

Upvotes: 0

Views: 117

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can amend your regex to

^(?:http(s)?:\/\/)[\w.-]+(?:\.[\w.-]+)+(?:\/[\w.~:?#[\]@!$&'()*+,;=.-]+)*\/?$

See the regex demo.

That is, replace [/]?[\w\-._~:?#[\]@!$&'()*+,;=./]+ with (?:\/[\w.~:?#[\]@!$&'()*+,;=.-]+)*\/?. This pattern part will make sure the / char is always separated from another / with at least one char.

Also consider replacing (?:\/[\w.~:?#[\]@!$&'()*+,;=.-]+)* with (?:\/[^\/]+)* if you do not care about what chars you can have in between /s, [^\/] matches any char but /.

Upvotes: 1

Related Questions