dongluanan7163 2013-03-07 17:35
浏览 191

正则表达式匹配包含子字符串但不包含子字符串的字符串

I'm trying to write a regex that will match a string that contains a certain substring, but fails if it also contains different substring. I've found this answer, but I'm not sure how to get it to work for my needs. In the interest of being specific as possible:

  • Yes, it has to do this as part of the expression. I do not have access to the code that will be processing this.
  • Yes, it needs to be one expression.
  • It needs to work with PHP's regex flavor. I'm pretty sure it's being evaluated using preg

To give an idea of what I'm trying to do, I have a set of URLs I'm trying to filter. URLs that have "/somedir" in them I want to match, but I don't want it to match if it also has "somestring" in the URL.

So,

  • www.somesite.com/somedir/index.html
  • www.somesite.com/somedir/somotherdir/index.html
  • www.somesite.com/somedir/somepage.html

would all match, but,

  • www.somesite.com/somedir/somestring.html
  • www.somesite.com/somedir/somestring/index.html

would both fail.

  • 写回答

1条回答 默认 最新

  • duangan6797 2013-03-07 18:01
    关注

    You need a regex that will accept a certain pattern only if it is not surrounded by another pattern:

    ~
        (?(DEFINE)
            (?<ACCEPT> must-contain-pattern)
            (?<REFUSE> must-not-contain-pattern)
        )
    
        ^
            (?:(?!(?&REFUSE)).)*
                (?&ACCEPT)
            (?:(?!(?&REFUSE)).)*
        $
    ~ux
    

    In the DEFINE block define the ACCEPT and REFUSE pattern according to your needs and this should work.

    Edit: The pattern from above tailored for the case of yours by defining the two named sub-patterns:

    ~
        (?(DEFINE)
            (?<ACCEPT> \Q/somedir\E)
            (?<REFUSE> \Qsomestring\E)
        )
    
        ^
            (?:(?!(?&REFUSE)).)*
                (?&ACCEPT)
            (?:(?!(?&REFUSE)).)*
        $
    ~ux
    
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路