Regex将特定URL与查询字符串匹配

Regex to Match Specific URL with Query String

本文关键字:查询 字符 字符串 串匹配 URL Regex      更新时间:2023-09-26

嗨,我正在尝试匹配一个允许查询字符串的特定URL。基本上我需要以下发生:

  • http://some.test.domain.com-通过
  • http://some.test.domain.com/-通过
  • http://some.test.domain.com/home-通过
  • http://some.test.domain.com/?id=999-通过
  • http://some.test.domain.com/home?id=888&rt=000-通过
  • http://some.test.domain.com/other-失败
  • http://some.test.domain.com/another?id=999-失败

以下是我目前所拥有的:

var pattern = new RegExp('^(https?:'/'/some'.test'.domain'.com('/{0,1}|'/home{0,1}))$');
if (pattern.test(window.location.href)){
    console.log('yes');   
}

上面的代码只适用于前三个,而不适用于查询字符串。如有任何帮助,我们将不胜感激。谢谢

这样的模式应该可以工作(至少对于您的特定域)

/^http:'/'/some'.test'.domain'.com('/(home)?('?.*)?)?$/

这将匹配一个文字http://some.test.domain.com(可选地,后跟所有文字/),可选地,紧跟文字home,可选地后跟文字?和任意数量的其他字符。

你可以在这里测试

不要使用Regex,使用URL解析器。您可以使用purl

然后,你会做:

url = "http://some.test.domain.com/home" // Or any other
purl(url).attr('path')  // is equal to "home" here.

您只需要对照您接受的路径(似乎是"""/""home")检查.attr('path')


以下是一些示例输出:

purl("http://some.test.domain.com/?qs=1").attr('path')
"/"
purl("http://some.test.domain.com/other").attr("path")
"/other"
purl("http://some.test.domain.com/home").attr("path")
"/home"