代码之家  ›  专栏  ›  技术社区  ›  Toleo

在未捕获的组上构建条件

  •  1
  • Toleo  · 技术社区  · 8 年前

    在以下内容中 正则表达式 :

    ((this)|(that))-((?(2)these|(?(3)those)))
    

    我接受以下两种情况之一:

    • 这个这些
    • 那那些

    对于 这个这些 我得到了 大堆 其中:

    Array ( 
        [0] => this-these 
        [1] => this 
        [2] => this 
        [3] => 
        [4] => these 
    ) 
    

    对于 那那些 我得到了 大堆 其中:

    Array ( 
        [0] => that-those 
        [1] => that 
        [2] => 
        [3] => that 
        [4] => those 
    ) 
    

    该数组类似于 Caputred集团 ,我只想捕捉 these those ,我不想拉任何其他组来获取以下数组:

    的情况 这个这些 :

    Array ( 
        [0] => this-these 
        [1] => these 
    ) 
    

    的情况 那那些 :

    Array ( 
        [0] => that-those 
        [1] => those 
    ) 
    

    我尝试了以下内容 正则表达式 s:

    (?:(this)|(that))-(?:(?(1)(these)|(?(2)(those))))
    

    但是得到了 大堆 其中:

    Array ( 
        [0] => that-those 
        [1] => 
        [2] => that 
        [3] => 
        [4] => those 
    ) 
    

    然后尝试 正则表达式 :

    (?:(?:this)|(?:that))-((?(1)(?:these)|(?(2)(?:those))))
    

    这是错误的,因为 (1), (2) 不存在。

    如何捕获非捕获组以对其应用条件或仅捕获我想要的组。


    其他情况如下:

    this-in-these
    this-on-those
    
    that-at-those
    that-as-these
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Wiktor Stribiżew    8 年前

    毕竟,似乎您甚至不需要任何条件构造,也不需要lookbehind。

    您正在寻找分组构造,即捕获组和非捕获组的组合:

    (?:this-[io]n|that-a[ts])-(these|those)
    

    请参见 regex demo

    这个 (?:this-[io]n|that-a[ts])-(these|those)

    • (?:this-[io]n|that-a[ts]) -匹配任一项 this-in ,则, this-on ,则, that-at that as (由于 非捕获组 (?:...) )
    • - -连字符
    • (these|those) -捕获组1:任一 these those

    您最初的问题可以通过查找来解决:

    (?:this|that)-((?<=this-)these|those)
    

    看见 this regex demo .但是,如果 this that 模式可能会有所不同,正则表达式可能无法工作,因为大多数正则表达式引擎不支持宽度未知的lookbehind模式,除非您正在使用。NET或最新Chrome版本中的JavaScript,或Python中的PyPi regex。

    在这里 (?:this|that) 非捕获组匹配 那个 ,然后匹配连字符,然后 这些 如果当前位置前面有 this- 那些 否则将捕获。