需要一个javascript正则表达式来匹配特定的路径

时间:2015-10-13 23:27:26

标签: javascript regex url

我需要帮助才能匹配仅在

时匹配的网址
  • 路径完全匹配/ gummybear /或/ gummybear(case casetive)
  • 协议是http或https
  • 域/主机/端口/哈希可以是任何
如果

,则正则表达式不应匹配
  • 路径是/ gummybear / foobar
  • 它包含搜索参数,例如?query = string

到目前为止我得到了这个:

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

的例子应该是真的
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/

的例子应该是假的
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

1 个答案:

答案 0 :(得分:6)

根据您的具体需求,我可以提出这个正则表达式:

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

Regular expression visualization

<强> Working demo

enter image description here

我没有逃脱斜线以使其更具可读性,但对于javascript,您可以使用:

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