3
我是相當新的正則表達式,我在perl腳本stubled在一個正則表達式最近,我無法弄清楚:正則表達式的解釋
$groups= qr/\(([^()]+|(??{$groups}))*\)/;
任何幫助,將不勝感激!
我是相當新的正則表達式,我在perl腳本stubled在一個正則表達式最近,我無法弄清楚:正則表達式的解釋
$groups= qr/\(([^()]+|(??{$groups}))*\)/;
任何幫助,將不勝感激!
那麼,如果你展開:
$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;
你得到一個優雅的遞歸方法找到平衡括號:)
的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}))*\)'
啊!這就說得通了。什麼是/ x最終我從來沒有見過。 – Kalamari
@Kalamari這是可用空間的標誌。它允許我以更易讀的方式編寫正則表達式,並在其中添加解釋。 – FailedDev
@Kalamari,'''/ x'''可以讓你把它分開,並且包含註釋。它基本上意味着「忽略白色空間......和評論」。 – FakeRainBrigand