【问题标题】:Regular expression that matches "articles" but not "articles-main"?匹配“articles”但不匹配“articles-main”的正则表达式?
【发布时间】:2023-03-31 22:50:01
【问题描述】:

我将如何编写一个正则表达式来匹配包含段 "articles" 后跟任何其他段的任何 URL,但不匹配带有段 "articles-main" 的 URL?

所以它会匹配这些:

www.mysite.com/articles
www.mysite.com/articles/tinman

但不是这些:

www.mysite.com/articles-main
www.mysite.com/articles-main/tinman

如果重要的话,这是在 ExpressionEngine 中使用的。

【问题讨论】:

  • article-main 在匹配中你真正要避免的唯一事情,或者你想避免在文章之前或之后有什么东西,例如还有www.mysite.com/my_articleswww.mysite.com/articles_new也不应该匹配?

标签: regex expressionengine


【解决方案1】:

使用所谓的否定前瞻

articles(?!-main)

或更准确地说:

mysite.com/articles(?!-main)

【讨论】:

    【解决方案2】:

    为了与@Regexident 的建议背道而驰,我建议积极向前看articles(?=$|\/)

    这是说匹配articles,看看它后面是/字符还是字符串的结尾。这样,无论您匹配的是 "articles-main" 还是 "articlessomethingelse",都无关紧要。

    这个不会做的是检查文章是否是它自己的目录。 http://example.com/some-articles 的值将匹配,这可能是不可接受的。

    如果您不关心匹配中是否包含 / 字符,您可以使用如下行的正则表达式:

    \/articles(?=\/|$)
    

    如果您确实关心并且您正在使用 PHP 的 pcre 函数,您可以使用积极的后视 ((?<=)):

    (?<=\/)articles(?=\/|$)
    

    More information about these regex assertions can be found on the php.net website.

    【讨论】:

      【解决方案3】:

      寻找“文章/”。对于您的示例,正​​则表达式可能有点矫枉过正。

      【讨论】:

      • 那不匹配www.mysite.com/articles
      • 使用正则表达式似乎是一个相当简单的案例。
      • 当然,毫无疑问。它虽然有效。 articles/ 没那么多。 ;)
      猜你喜欢
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多