【问题标题】:RegEx for matching a URL containing one word and excluding another [duplicate]RegEx 用于匹配包含一个单词并排除另一个单词的 URL [重复]
【发布时间】:2019-05-21 18:04:37
【问题描述】:

我找到了一个正则表达式的例子,如果一个字符串不包含特定的单词,它将匹配。但我正在寻找匹配的东西,如果它包含一个单词而不是另一个单词。示例:

我正在处理基于 RegEx 的 URL 排除。如果 URL 包含 collections 而不是 products,我希望它匹配

如果不包含 products,我发现的正则表达式是这样的:^((?!products).)*$ 效果很好,但任何时候我添加检查以确保其中包含集合,它每次都会失败。

这是一个我不希望它匹配的示例网址:

https://dummysite.com/collections/frontpage/products/myproduct

如果是这样的话:

https://dummysite.com/collections/frontpage/

应该匹配。

我该如何解决这个问题?

【问题讨论】:

  • 对于这种简单的情况,我不建议使用 RegEx。它很慢。试试 ES6 includes()。
  • @k3llydev 我同意 100% 但不幸的是无法控制它的使用。无论如何,每次页面加载只会发生一次,所以没什么大不了的。

标签: javascript regex regex-negation regex-lookarounds regex-greedy


【解决方案1】:

您可以使用正向预测

(?!.*products)(?=.*collections)
      |               |___________  Positive lookahead ( For must condition)
      |___________________________  Negative lookahead ( For must not condition)

let urls = ['https://dummysite.com/collections/frontpage/products/myproduct','https://dummysite.com/collections/frontpage/']

urls.forEach(url=>{
  console.log(url, '\nResult --->', /^(?!.*products)(?=.*collections).*$/.test(url))
})

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多