regex - PCRE(递归)模式匹配包含正确括号子字符串的字符串。为什么这个会失败?

标签 regex perl 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

无法匹配带有嵌套括号的字符串:“(())”

最佳答案

它不会失败

$ 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";
}

关于regex - PCRE(递归)模式匹配包含正确括号子字符串的字符串。为什么这个会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2973630/

相关文章:

java - 如何拆分以逗号分隔的字符串,但在 Java 中排除一些包含逗号的单词

用于替换字符串的正则表达式

perl - 是否有列出美国邮政编码和州的 CPAN 模块?

performance - Haskell 程序与 Perl 相比性能低下

regex - Oracle 18c - REGEXP_REPLACE 的替代方案

perl - 3G 调制解调器中的错误检测

regex - sed 中的非贪婪(不情愿)正则表达式匹配?

c - GCC 编译器无法找到 pcre.h

正则表达式仅在字符序列之后匹配出现

c++ - 使用 Qt 的正则表达式捕获一些文本