【问题标题】:Need a javascript regex to match a specific path需要一个 javascript 正则表达式来匹配特定路径
【发布时间】:2016-01-11 21:17:12
【问题描述】:

我需要帮助来匹配一个仅在以下情况下才匹配的网址

  • 路径完全匹配 /gummybear/ 或 /gummybear(区分大小写)
  • 协议是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

【问题讨论】:

  • 你的“应该匹配”https://example.com:81/gummybear/#/exaple/1234/和你的“不应该匹配”the path is /gummybear/foobar有什么区别?
  • @FedericoPiazza 它匹配另一个子目录

标签: javascript regex url


【解决方案1】:

针对您的特定需求,我可以提出这个正则表达式:

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

Working demo

我没有转义斜杠以使其更具可读性,但是对于 javascript,您可以使用:

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

【讨论】:

  • 您使用什么工具来生成该图表?它在 regex101 上吗?在哪里?
  • @SkeetsO'Reilly 我用过Debuggex Demo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 2020-09-30
  • 2018-03-29
相关资源
最近更新 更多