2011-12-10 54 views
3

我是相当新的正则表达式,我在perl脚本stubled在一个正则表达式最近,我无法弄清楚:正则表达式的解释

$groups= qr/\(([^()]+|(??{$groups}))*\)/; 

任何帮助,将不胜感激!

回答

10

那么,如果你展开:

$groups= qr/ 
    \(    # match an open paren (
    (    # followed by 
     [^()]+   # one or more non-paren character 
    |    # OR 
     (??{$groups}) # the regex itself 
    )*    # repeated zero or more times 
    \)     # followed by a close paren) 
/x; 

你得到一个优雅的递归方法找到平衡括号:)

+0

啊!这就说得通了。什么是/ x最终我从来没有见过。 – Kalamari

+1

@Kalamari这是可用空间的标志。它允许我以更易读的方式编写正则表达式,并在其中添加解释。 – FailedDev

+0

@Kalamari,'''/ x'''可以让你把它分开,并且包含注释。它基本上意味着“忽略白色空间......和评论”。 – FakeRainBrigand

2

YAPE::Regex::Explain模块可以告诉你什么是正则表达式是这样做的:

% perl5.14.2 -MYAPE::Regex::Explain -E 'say YAPE::Regex::Explain->new(shift)->explain' '\(([^()]+|(??{$groups}))*\)' 
The regular expression: 

(?-imsx:\(([^()]+|(??{$groups}))*\)) 

matches as follows: 

NODE      EXPLANATION 
---------------------------------------------------------------------- 
(?-imsx:     group, but do not capture (case-sensitive) 
         (with^and $ matching normally) (with . not 
         matching \n) (matching whitespace and # 
         normally): 
---------------------------------------------------------------------- 
    \(      '(' 
---------------------------------------------------------------------- 
    (      group and capture to \1 (0 or more times 
          (matching the most amount possible)): 
---------------------------------------------------------------------- 
    [^()]+     any character except: '(', ')' (1 or 
          more times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    (??{$groups})   run this block of Perl code (that isn't 
          interpolated until RIGHT NOW) 
---------------------------------------------------------------------- 
)*      end of \1 (NOTE: because you are using a 
          quantifier on this capture, only the LAST 
          repetition of the captured pattern will be 
          stored in \1) 
---------------------------------------------------------------------- 
    \)      ')' 
---------------------------------------------------------------------- 
)      end of grouping 
---------------------------------------------------------------------- 

您可以将这一行代码变成您个人资料中的别名:

alias re="perl -MYAPE::Regex::Explain -E 'say YAPE::Regex::Explain->new(shift)->explain'" 

之后,你不必记住所有:

re '\(([^()]+|(??{$groups}))*\)'