2017-08-25 11 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

は何に基づいて、第1のものは受け入れられ、最後のものはないのですか? –

+0

このhttp://regexr.com/のような正規表現のビルダーを使用すると、おそらく役に立ちます。 – Andy

+0

あなたが言っていることは、それらの文字列に '/ shop /'と '/ 08 /'と '/ 25 /'の有効な月の '/ 2017'があることを確認したいだけですが、 '/ string-of-text/another-string-of /'の最後に? – NewToJS

答えて

1

あなたが/、あなたはドンかなり確信して」をエスケープする必要があります最後に/の後にあるものと一致するので、最後に.*を入れたいと思います。試してみてください/^\/shop\/\d{4}\/\d{2}\/\d{2}(?:\/[^/]+){2}\/?$/;

  • ^\/shop/shopの冒頭に一致します。
  • \/\d{4}\/\d{2}\/\d{2}は、/year/month/dayと一致します。
  • (?:\/[^/]+){2}\/?$は、別の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