代码之家  ›  专栏  ›  技术社区  ›  Prathamesh Rasam

带有URL模式集的匹配URL包含正则表达式

  •  0
  • Prathamesh Rasam  · 技术社区  · 6 年前

    我有一个URL,它应该与多个URL模式数组中的一个URL模式匹配

    var URLPatternsArr = ['https://m.abc.com/collections/([^/]+)','https://m.abc.com/store/([^/]+)/','https://m.abc.com/collections/([^/]+)/item/([^/]+)']
    
    url = 'https://m.abc.com/collections/tagline-silk-mill/item/green-embroidered-faux-georgette-salwar-anarkali-salwar-kameez--42cba667-256a-4f95-8912-62f3d03a128f'
    

    URLPatternsArr将包含n个带有regex的不同URL。我将迭代这个数组&检查精确匹配。 如果我使用javascript匹配函数

     Object.keys(URLPatternsArr).forEach(function(el) {
         console.log("-------");
         console.log("matching with "+URLPatternsArr[el]);
            if(url.match(URLPatternsArr[el])  != null)
            {
              console.log("matched with "+URLPatternsArr[el]);
            }
          });
    

    url与两者都匹配 'https://m.abc.com/collections/([^/]+)' 'https://m.abc.com/collections/([^/]+)/item/([^/]+)' ,

    我想把这个URL和 'https://m.abc.com/collections/([^/]+)/item/([^/]+)' 因为这两个正则表达式之间的模式contians/item/和URL包含相同的内容。 在javascript或节点中找到这种类型匹配的好方法是什么。js?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bsquare ℬℬ    6 年前

    只需改变你的模式以完全匹配:

    var URLPatternsArr = ['^https://m.abc.com/collections/([^/]+)$','^https://m.abc.com/store/([^/]+)/$','^https://m.abc.com/collections/([^/]+)/item/([^/]+)$']