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

我试图用正则表达式匹配下面的路径。


# 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.

我做错了什么,我该如何解决?


DIEA
浏览 250回答 3
3回答

陪伴而非守候

您可以使用否定字符类^(?:[^\/]*\/){2}[^\/]*const path = '/content/test-site/en_US/abc.html';const desired = path.match(/^(?:[^\/]*\/){2}[^\/]*/)console.log(desired[0])

蝴蝶不菲

这是另一种方法:(?:\/[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 /

开心每一天1111

正则表达式匹配任何字符期望/:content\/[^\/]+这是字符类。以脱字符开头的字符类将匹配该类中没有的任何内容。更多关于这一点。因此,使用 javascript:const url = '/content/test-site/en_US/abc.html';const path = url.match(/content\/[^\/]+/)console.log(path[0])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript