2010-06-04 1 views
3

음, 다른 방법 (음 ... 또는 오히려 작동하는 방법)이 있지만, 질문은 왜 이것이 실패합니까?괄호로 묶은 부분 문자열이 포함 된 문자열과 일치하는 PCRE (재귀) 패턴입니다. 왜 이것이 실패할까요?

/ 
\A    # start of the string 
(    # group 1 
(?:    # group 2 
[^()]*   # something other than parentheses (greedy) 
|    # or 
\((?1) \)  # parenthesized group 1 
)    # -group 2 
+    # at least once (greedy) 
)    # -group 1 
\Z    # end of the string 
/x 

중첩 된 괄호가있는 문자열과 일치 실패 : "(())"

답변

4

와우 .. 정크 감사 실패하지 않습니다! Perl에서 정말 효과가 있습니다. 그러나 PCRE에는 없습니다. 그래서, "펄과 PCRE 정규식 패턴 매칭의 차이점은 무엇입니까?"

그리고 voila! 답이있다 : 펄

In PCRE (like Python, but unlike Perl), a recursive subpattern call is 
always treated as an atomic group. That is, once it has matched some of 
the subject string, it is never re-entered, even if it contains untried 
alternatives and there is a subsequent matching failure. 

에서

재귀의 차이는 따라서, 우리는 단지 두 개의 서브 패턴을 교체해야합니다

/ \A ((?: \((?1) \) | [^()]*)+) \Z /x 

감사합니다!

7

그것은

$ perl junk.pl 
matched junk >(())< 

$ cat junk.pl 
my $junk = qr/ 
\A    # start of the string 
(    # group 1 
(?:    # group 2 
[^()]*   # something other than parentheses (greedy) 
|    # or 
\((?1) \)  # parenthesized group 1 
)    # -group 2 
+    # at least once (greedy) 
)    # -group 1 
\Z    # end of the string 
/x; 

if("(())" =~ $junk){ 
    print "matched junk >$1<\n"; 
}