what's the regular expression to find two sets of parenthesis in a row using perl?

前端 未结 3 1190
我在风中等你
我在风中等你 2021-01-23 09:26

I have rows with different sets of parenthesis. For example

     (sdfsfs) (sfdsfd) 
     (sdfsfs) (sfdsfd) (sfdsfd) 
     (sdfsfs) (sfdsfd) (sfdsfd) (sfdsfd)
            


        
相关标签:
3条回答
  • 2021-01-23 09:35
    ^(?:\s*\([^\)(]*\)\s*){2}$
    

    You can define this pattern with anchors.See demo.

    https://regex101.com/r/eX9gK2/10

    0 讨论(0)
  • 2021-01-23 09:41

    You can use this regex to match a line with exactly 2 parentheses sets:

    m/^(\([^)]*\)\s*){2}$/
    

    OR:

    m/^\([^)]*\)\s*\([^)]*\)$/
    

    RegEx Demo

    [^)]* will match any character but ) and is more efficient than .*? or .*.

    0 讨论(0)
  • 2021-01-23 09:46

    This is a better solution.

    while ( $text =~ //(?m)^(?=(?:.*?(?&parens)){2})(?!(?:.*?(?&parens)){3}).+$(?(DEFINE)(?<parens>\([^)\n]*\)))/g )
    {
        print $&,"\n";
    }
    

    Formatted:

     (?m)                          # Multi-line mode
     ^                             # BOL
     (?=                           # Must be 2 paren's blocks
          (?:
               .*? (?&parens) 
          ){2}
     )
     (?!                           # Cannot be 3 paren's blocks
          (?:
               .*? (?&parens) 
          ){3}
     )
     .+                            # Get the entire line
     $                             # EOL
    
     (?(DEFINE)
          (?<parens> \( [^)\n]* \) )    # (1)
     )
    
    0 讨论(0)
提交回复
热议问题