我试图用正则表达式匹配下面的路径。# test-site could be anything like "shoe-site", "best-clock", etc./content/test-site当前的正则表达式规则(\/content\/{1}\S+)就足够了。问题是它匹配整个路径,例如/content/test-site/en_US/abc.html.我只需要匹配/content/test-site.要匹配的路径示例:https://localhost:4502/content/test-site/en_US/book/city/sample-rooms/airport-inn/propertyCode.00000.html到目前为止我尝试过的正则表达式;(\/content\/[a-z-]+)\/[a-z]{2}_[A-Z]{2}\/book(ing-path)?\/(sample-|sample-details)(.*).[0-9]{5}.*/content/test-site is optional- it might not present sometimes in url.我做错了什么,我该如何解决?
3 回答
![?](http://img1.sycdn.imooc.com/545863c10001865402200220-100-100.jpg)
陪伴而非守候
TA贡献1757条经验 获得超8个赞
您可以使用否定字符类
^(?:[^\/]*\/){2}[^\/]*
const path = '/content/test-site/en_US/abc.html';
const desired = path.match(/^(?:[^\/]*\/){2}[^\/]*/)
console.log(desired[0])
![?](http://img1.sycdn.imooc.com/5333a0780001a6e702200220-100-100.jpg)
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
这是另一种方法:
(?:\/[a-zA-Z0-9-]+){2}
解释:
(?: # Non-capturing group
\/[a-zA-Z0-9-]+ # Match starting with / and followed with characters/digits/-
) # Close grouping
{2} # Match two times, i.e. only match with two /
![?](http://img1.sycdn.imooc.com/5458472300015f4702200220-100-100.jpg)
开心每一天1111
TA贡献1836条经验 获得超13个赞
正则表达式匹配任何字符期望/:
content\/[^\/]+
这是字符类。以脱字符开头的字符类将匹配该类中没有的任何内容。更多关于这一点。
因此,使用 javascript:
const url = '/content/test-site/en_US/abc.html';
const path = url.match(/content\/[^\/]+/)
console.log(path[0])
添加回答
举报
0/150
提交
取消