【发布时间】:2014-05-03 01:45:54
【问题描述】:
看到this question,开始更深入地思考捕获组。
例如有下一个(示例)输入:
text (aaa (text) ccc)
text ( aaa (text) ccc )
text ( ' aaa (text) ccc ' )
text ( " aaa (text) ccc " )
text (aaa ( ' text ' ) ccc)
text ( aaa ( ' text ' ) ccc )
text ( ' aaa ( " text " ) ccc ' )
text ( " aaa ( ' text ' ) ccc " )
想要捕获anyhing什么代替aaatext(在中间)和ccc,所以想要的结果:
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
=aaa= =text= =ccc=
我有 3 个正则表达式解决方案:
use strict;
use warnings;
while(<DATA>){
chomp;
m/
.*? #non greedy anything up to
text #the first "text"
\s* #optional spaces
\( #opening (
(.*) #content inside () greedy -> $1
\) #closing )
\s*$
/x;
#processing only the captured content with removed outside ()
#remove outside ' or " and extra spaces
my $inside = $1;
$inside =~ m/
#at the begining of "line"
^\s* #optional spaces
["']? #optional " or '
\s* #optional spaces
(.*?) #content - non greedy -> $1
#at the end of "line"
\s* #optional spaces before the closing ' "
['"]? #optional closing " or '
\s*$ #optionalny spaces
/x;
$inside = $1;
$inside =~ m/
^(\w+) #any word at the start -> $1
\s* #optional spaces
\( #opening (
\s* #optional spaces
['"]? #optional ' or "
\s* #spaces
(.*?) #the content inside ' " -> $2
\s* #any spaces
['"]? #optional "'
\s* #sp
\) #closing )
\s* #spaces
(\w+)$ #word at the end -> $3
/x;
print "=$1= =$2= =$3=\n";
}
__DATA__
text (aaa (text) ccc)
text ( aaa (text) ccc )
text ( ' aaa (text) ccc ' )
text ( " aaa (text) ccc " )
text (aaa ( ' text ' ) ccc)
text ( aaa ( ' text ' ) ccc )
text ( ' aaa ( " text " ) ccc ' )
text ( " aaa ( ' text ' ) ccc " )
问题:
- 是否可以将上述所有 3 个正则表达式合并为一个?
- 如果是,这是否普遍可行?那么可以将 ANY 数量的后续匹配正则表达式与捕获组组合成 one 正则表达式吗? (仅表示
m//与捕获组匹配,而不是后续替换正则表达式) - 如果是,什么时候更希望使用一个正则表达式而不是更多?例如什么时候更快更多的正则表达式,当一个大的时候?
Ps:我知道Text::Ballanced 的存在,但这个问题更多的是关于“正则表达式的可能性”。
【问题讨论】: