2011-12-10 22 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 
---------------------------------------------------------------------- 

このワンライナーをあなたのプロフィールのエイリアスにすることができます:

その後

、あなたはすべてのことを覚えておく必要はありません。

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