为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式匹配精确路径与两个 /

正则表达式匹配精确路径与两个 /

DIEA 2021-10-07 10:44:22
我试图用正则表达式匹配下面的路径。# 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 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您可以使用否定字符类

^(?:[^\/]*\/){2}[^\/]*

//img1.sycdn.imooc.com//615e5f230001224e04910189.jpg

const path = '/content/test-site/en_US/abc.html';


const desired = path.match(/^(?:[^\/]*\/){2}[^\/]*/)


console.log(desired[0])


查看完整回答
反对 回复 2021-10-07
?
蝴蝶不菲

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 /


查看完整回答
反对 回复 2021-10-07
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

正则表达式匹配任何字符期望/:


content\/[^\/]+

这是字符类。以脱字符开头的字符类将匹配该类中没有的任何内容。更多关于这一点。


因此,使用 javascript:


const url = '/content/test-site/en_US/abc.html';


const path = url.match(/content\/[^\/]+/)


console.log(path[0])


查看完整回答
反对 回复 2021-10-07
  • 3 回答
  • 0 关注
  • 249 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信