admin管理员组

文章数量:1290952

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

:81/gummybear/

:81/gummybear#/foobar/?search=params
:81/gummybear
:81/gummybear/#/exaple/1234/

examples that it should be false for

:81/foo/gummybear/
:81/guMmybear/
:81/gummybear.html

file://example:81/gummybear#/foobar/?search=params
:81/gummybear?search=apple#lol
:81/#/gummybear/
:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top

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.:81/gummybear/
http://www.example./gummybear#top
https://example.:81/gummybear#/foobar/?search=params
http://www.exa.mple.:81/gummybear
https://example.:81/gummybear/#/exaple/1234/

examples that it should be false for

https://www.example.:81/foo/gummybear/
https://www.example.:81/guMmybear/
https://www.example.:81/gummybear.html
http://www.example./gummybear/apple#top
file://example.:81/gummybear#/foobar/?search=params
http://www.exa.mple.:81/gummybear?search=apple#lol
https://example.:81/#/gummybear/
http://www.test.:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top
Share Improve this question asked Oct 13, 2015 at 23:27 EndlessEndless 37.9k13 gold badges116 silver badges137 bronze badges 2
  • What are the differences between your "should match" https://example.:81/gummybear/#/exaple/1234/ and your "shouldn't match" the path is /gummybear/foobar ? – Federico Piazza Commented Oct 13, 2015 at 23:49
  • @FedericoPiazza it matches another sub directory – Endless Commented Oct 14, 2015 at 0:04
Add a ment  | 

1 Answer 1

Reset to default 9

For your specific needs, I can e 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(?:\/?|\/?#.*)$

本文标签: Need a javascript regex to match a specific pathStack Overflow