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

正则表达式:如果后面跟着一组运算符,如何捕获括号组?[副本]

  •  1
  • user1561108  · 技术社区  · 6 年前
    \(([^\\(\\)]+)\)
    

    上面的regex捕获了表单中每一组括号之间的所有内容

    (Hello OR there) AND (big AND wide AND world)
    

    我明白了

    Hello OR there
    big AND wide AND world
    

    但当括号内有括号时,它就会掉下来

    (Hello OR there AND messing(it)up) AND (big AND wide AND world)
    

    it
    big AND wide AND world
    

    既然我想

    Hello OR there AND messing(it)up
    big AND wide AND world
    

    我不确定regex是否能做到,或者最好的方法是什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Paolo    6 年前

    您可以使用以下模式:

    \(((?:[^()]+|(?R))*+)\)
    

    这个 (?R) recurses the entire pattern if possible .

    你可以试试 here


    输入:

    (Hello OR there AND messing(it)up) AND (big AND wide AND world)
    

    捕获的组包括:

    Group 1.    47-79   `Hello OR there AND messing(it)up`
    Group 1.    86-108  `big AND wide AND world`
    

    如果您使用的是Python,则可以使用 regex

    import regex
    
    mystring = '(Hello OR there AND messing(it)up) AND (big AND wide AND world)'
    print(regex.findall('(?V1)\(((?:[^()]+|(?R))*+)\)',mystring))
    

    印刷品:

    ['Hello OR there AND messing(it)up', 'big AND wide AND world']