RegEx将几个URL模式与Javascript匹配

RegEx将几个URL模式与Javascript匹配,javascript,regex,url,Javascript,Regex,Url,我正在尝试匹配Javascript中的任意一种URL模式。这些模式是: 主页-之后没有任何内容的/ 三个解决方案页面之一。每个解决方案(编号)后面可以跟一个/和后面的任何字符。 /solutions/99043或/solutions/99043/blah /solutions/60009或/solutions/60009/blah /solutions/40117或/solutions/40117/blah 搜索:/Search后跟任何字符,例如?blah 我尝试的正则表达式如下: /\

我正在尝试匹配Javascript中的任意一种URL模式。这些模式是:

  • 主页-之后没有任何内容的
    /
  • 三个解决方案页面之一。每个
    解决方案(编号)
    后面可以跟一个
    /
    和后面的任何字符。
    • /solutions/99043
      /solutions/99043/blah
    • /solutions/60009
      /solutions/60009/blah
    • /solutions/40117
      /solutions/40117/blah
  • 搜索:
    /Search
    后跟任何字符,例如
    ?blah
我尝试的正则表达式如下:

/\/$|\/solutions\/(99043|60009|40117)\/.*|\/search.*/
在该功能中:

(function () {
    const urlPath = window.location.pathname;
    if (urlPath.match(/\/$|\/solutions\/(99043|60009|40117)\/.*|\/search.*/)) {
        console.log("urlPath", urlPath);
    }
})()
这是行不通的,因为一切似乎都是匹配的。有人知道我哪里出错了吗

根据注释,匹配但不应匹配的URL示例:
/solutions/

\/(solutions|search)(\/(99043|60009|40117).*|)

如果要从URL提取路径名,然后执行匹配,我建议使用
^\/$
而不是只匹配“以斜杠结尾”

这就是
^\/$\/solutions\/(99043 60009 40117)\/.*\/search.


您可以在regex101.com上进行测试。我发现regulex对于可视化正则表达式非常有用

您可以使用以下正则表达式:

^\/((solutions(\/(99043|60009|40117)(\/.*)?)?)|search(.*)?)$
测试:

^\/((solutions(\/(99043|60009|40117)(\/.*)?)?)|search(.*)?)$
var regex=/^\/(解决方案(\/(99043-60009-40117)?(\/.*))?搜索(.*)$/
console.log(1,regex.test('/')//true
console.log(2,regex.test('/solutions'))//true
console.log(3,regex.test('/solutions/')//true
console.log(4,regex.test('/solutions/99043')//true
console.log(5,regex.test('/solutions/99043/')//true
console.log(6,regex.test('/solutions/99043/anything')//true
console.log(7,regex.test('/solutions/60009'))//true
console.log(8,regex.test('/solutions/60009/')//true
console.log(9,regex.test('/solutions/60009/anything')//true
console.log(10,regex.test('/solutions/40117'))//true
console.log(11,regex.test('/solutions/40117/')//true
console.log(12,regex.test('/solutions/40117/anything')//true
console.log(13,regex.test('/solutions/00000')//false
console.log(14,regex.test('/solutions/00000/')//false
console.log(15,regex.test('/solutions/00000/anything')//false
console.log(16,regex.test('/bug'))//false
console.log(17,regex.test('/search?query=javascript')//true

console.log(18,regex.test('/search/?query=javascript')//true
您可以使用多个锚来断言字符串的开头
^
和结尾
$

匹配
/
,并可选择将零件与后跟3个数字的解决方案匹配,或使用匹配的搜索零件

  • ^
    字符串的开头
  • \/
    匹配
    /
  • (?:
    非捕获组
    • solutions\/
      Match
      solutions/
    • (?:99043 | 60009 | 40117)
      匹配3个数字中的1个
    • (?:\/.*)
      可以选择匹配
      /
      和除换行符以外的任何字符0+次
    • |
    • search\b.*
      Match search后跟不匹配的单词边界,例如
      search here
  • )?
    关闭非捕获组并将其设置为可选
  • $
    字符串结尾

您能提供一些出现意外行为的测试用例吗?@Bazza我用一个例子更新了问题。也匹配以给定数字点开头的数字,以获得最简单的答案,但它不处理
/
(主页)场景。
^
字符串的开始导致我的正则表达式由于某种原因失败,但是解决方案或条件中的附加
?:
修复了单独传递
/solutions/
的场景。
^
将模式锚定到字符串的开始,并将
$
锚定到结尾。在这种情况下,您可以移除锚定。
/solutions/
不能是独立的:它后面必须跟在提供的三个数字中的任何一个。