简体   繁体   中英

Need a javascript regex to match a specific path

I need help to match a url that matches only if

  • the path matches exactly /gummybear/ or /gummybear (case sensetive)
  • the protocol is http or https
  • the domain/host/port/hash can be anything

the regex should not match if

  • the path is /gummybear/foobar
  • it contains search parameters such as ?query=string

So far i got this:

/^http[s]?:\/\/?[^\/\s]+\/gummybear[\/]?/

examples it should be true for

https://www.example.com:81/gummybear/
http://www.example.com/gummybear#top
https://example.com:81/gummybear#/foobar/?search=params
http://www.exa.mple.com:81/gummybear
https://example.com:81/gummybear/#/exaple/1234/

examples that it should be false for

https://www.example.com:81/foo/gummybear/
https://www.example.com:81/guMmybear/
https://www.example.com:81/gummybear.html
http://www.example.com/gummybear/apple#top
file://example.com:81/gummybear#/foobar/?search=params
http://www.exa.mple.com:81/gummybear?search=apple#lol
https://example.com:81/#/gummybear/
http://www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top

For your specific needs, I can come up with this regex:

^https?://[^/]+/gummybear(?:/?|/?#.*)$

正则表达式可视化

Working demo

在此输入图像描述

I haven't escaped slashes to make it more readable, but for javascript you can use:

^https?:\/\/[^\/]+\/gummybear(?:\/?|\/?#.*)$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM