2017-08-25 14 views
0

我想匹配與數字和文本混合的特定格式。數字是不同的日期。具有多個目錄的URL的正則表達式

這些應該符合:

/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/(.*?)/(.*)/(.*)/(.*)/(.*)$

+0

在什麼基礎上的第一批被接受,最後哪些不是? –

+0

使用像這樣的正則表達式生成器http://regexr.com/可能會幫助你。 – Andy

+0

所以你要說的是你要確保那些字符串有'/ shop /'和一個有效月份'/ 08 /'和''/ 25 /''一年''2017',但是也有很多附加的字符串在結尾'/字符串的文本/另一字符串的文本/'? – NewToJS

回答

1

你需要躲避/和非常肯定你不」 t最後要放.*,因爲這將在最後的/之後匹配任何東西,這不會是你所需要的;試試這個/^\/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)) 
 
);

+1

是的,謝謝! :) – Samantha