Regex Perl正则表达式捕获的缩写形式
我只想将第一个捕获组放入同一个变量中。事实上,我正在寻找一个简短的形式:Regex Perl正则表达式捕获的缩写形式,regex,perl,Regex,Perl,我只想将第一个捕获组放入同一个变量中。事实上,我正在寻找一个简短的形式: $_ = $1 if m/$prefix($pattern)$suffix/; 比如: s/$prefix($pattern)$suffix/$1/a; ## Where a is the option I am looking for 或者更好: k/$prefix($pattern)$suffix/; ## Where k is also an option I wish I can use... 这将避免需要匹
$_ = $1 if m/$prefix($pattern)$suffix/;
比如:
s/$prefix($pattern)$suffix/$1/a; ## Where a is the option I am looking for
或者更好:
k/$prefix($pattern)$suffix/; ## Where k is also an option I wish I can use...
这将避免需要匹配所有文本,从而产生更复杂的行:
s/^.*$prefix($pattern)$suffix.*$/defined $1 ? $1 : ""/e;
有什么线索吗
这对于本例非常有用:
push @array, {id => k/.*\s* = \s* '([^']+)'.*/};
而不是
/.*\s* = \s* '([^']+)'.*/;
my $id = '';
$id = $1 if $1;
push @array, {id => $id};
编辑:
我刚刚发现了一个有趣的方法,但如果未定义$1
,我将得到一个错误:(
您可以使用
/r
开关返回更改后的字符串,而不是对变量进行替换。根本不需要捕获任何内容。只需去掉前缀和后缀,然后将该操作的结果添加到数组中即可
use Data::Dump;
my @strings = qw( prefixcontent1suffix prefixcontent2suffix );
my @array = map { s/^prefix|suffix$//gr } @strings;
dd @array;
__END__
("content1", "content2")
如果您希望它是可配置的,那么这个如何:
my $prefix = qr/.+\{\{/;
my $suffix = qr/\}\}.+/;
my @strings = ( '{fo}o-_@09{{content1}}bar42' );
my @array = map { s/^$prefix|$suffix$//gr } @strings;
dd @array;
__END__
"content1"
在列表上下文中,
m/
操作符将捕获作为列表返回。这意味着您可以执行以下操作:
($_) = m/$prefix($pattern)$suffix/;
或者这个:
my ($key, $value) = $line =~ m/^([^=]+)=([^=]+)$/;
使用
在使用捕获组之前,您始终希望确保正则表达式匹配。通过使用三元表达式,您可以指定默认值,也可以指定未找到匹配项
或者,您可以在if语句中使用捕获组的列表形式,并让else输出警告:
if (my ($var) = /$prefix($pattern)$suffix/) {
...;
} else {
warn "Unable to find a match";
}
该死的,我还不够清楚。$prefix和$suffix只是包含了我正在寻找的东西的模式,即,
$prefix='{{{};$suffix='}}}};我的$strings='{fo}o-@09{{{content1}bar42'
@coin所以你仍然想从中获得content1
?请看我的编辑。很明显,前缀
是模式,但我想你可以自己改变它……请注意,/r
是。
my $var = /$prefix($pattern)$suffix/ ? $1 : '';
if (my ($var) = /$prefix($pattern)$suffix/) {
...;
} else {
warn "Unable to find a match";
}