具有多个目录的URL的正则表达式

时间:2017-08-25 00:41:59

标签: javascript regex

我正在尝试匹配与数字和文本混合的特定格式。这些数字是不同的日期。

这些应匹配:

/shop/2017/12/04/string-of-text/another-string-of-text

/shop/2017/12/04/string-of-text/another-string-of-text/

这些不应该:

/shop/2017/12/04/string-of-text/another-string-of-text/more-text

/shop/2017/12/04/string-of-text/

/shop/2017/12/04/string-of-text

这甚至可能吗?

到目前为止,我已经做到了这一点,但它似乎在某些情况下不匹配:

^/shop/(.*?)/(.*)/(.*)/(.*)/(.*)$

1 个答案:

答案 0 :(得分:1)

您需要逃避/,并且确定您不希望将.*放在最后,因为这将匹配最后/之后的任何内容,这将不是什么你需要;试试这个/^\/shop\/\d{4}\/\d{2}\/\d{2}(?:\/[^/]+){2}\/?$/;

  • ^\/shop在开头匹配/shop;
  • \/\d{4}\/\d{2}\/\d{2}/year/month/day;
  • 相匹配
  • (?:\/[^/]+){2}\/?$匹配另外两个文本块,最后带有可选的/;

var samples = ["/shop/2017/12/04/string-of-text/another-string-of-text", 
               "/shop/2017/12/04/string-of-text/another-string-of-text/", 
               "/shop/2017/12/04/string-of-text/another-string-of-text/more-text", 
               "/shop/2017/12/04/string-of-text/", 
               "/shop/2017/12/04/string-of-text"]

console.log(
  samples.map(s => /^\/shop\/\d{4}\/\d{2}\/\d{2}(?:\/[^/]+){2}\/?$/.test(s))
);