我有-让-比方说- example.com网站和那里我有account页面。它可能有GET参数,这也被认为是帐户页面的一部分。它也可以具有URL片段。如果它是home.html片段-它仍然是帐户页面。如果是另一个片段,那么它就是帐户页面的另一个子页面。
所以-我需要一个RegEx (JS)来匹配这个案例。这就是我到目前为止成功构建的:
example.com\/account\/(|.*\#home\.html|(\?(?!.*#.*)))$https://regex101.com/r/ihjCIg/1
前4个是我需要的案例。如您所见,第二行与我的RegEx不匹配。
这里我漏掉了什么?
发布于 2019-08-27 20:00:18
您可以创建2个可选组,1个用于选择性地匹配?并匹配除#之外的任何字符,另一个可选组与#home.html匹配
注意转义圆点以匹配字面意思。
^example\.com\/account\/(?:\?[^#\r\n]*)?(?:#home\.html)?$^开始stringexample\.com\/account\/匹配start(?:非捕获组\?[^#\r\n]*匹配?和0+乘以除#或newline之外的任何字符
关闭
)?组并将其设置为optional(?:非捕获组#home\.html Match #home.html
关闭
)?组并将其设置为optional$
let pattern = /^example\.com\/account\/(?:\?[^#\r\n]*)?(?:#home\.html)?$/;
[
"example.com/account/",
"example.com/account/?brand=mine",
"example.com/account/#home.html",
"example.com/account/?brand=mine#home.html",
"example.com/account/#other.html",
"example.com/account/?brand=mine#other.html"
].forEach(url => console.log(url + " --> " + pattern.test(url)));
发布于 2019-08-27 19:40:50
组中的第三个备选方案具有负面的前瞻性,这确保它拒绝任何包含#的文本,但您没有特别提到任何应该与其余内容匹配的内容,直到行尾。查看这个更新的正则表达式演示,
https://regex101.com/r/ihjCIg/3
如果你注意到了,我已经在com之前避开了你的第一个点,并在负前视部分之后添加了.*,以便它与你的第二个样本相匹配。
发布于 2019-08-27 19:44:57
example\.com\/account\/((\??[^#\r\n]+)?(#?home\.html)?)?$这与您的前四个字符串匹配
example.com/account/
example.com/account/?brand=mine
example.com/account/#home.html
example.com/account/?brand=mine#home.html不包括你的最后两个
example.com/account/#other.html
example.com/account/?brand=mine#other.htmlhttps://stackoverflow.com/questions/57673669
复制相似问题