如何捕获全局正则表达式替换中的每个匹配项?
How to capture every match in a global regex substitution?
我意识到可以通过一些小的变通方法来实现这一点,但我希望有更简单的方法(因为我经常使用这种类型的表达式)。
给定示例字符串:
my $str = "An example: sentence!*"
可以使用正则表达式来匹配每个标点符号并将它们捕获到一个数组中。
此后,我可以简单地重复正则表达式并替换匹配项,如下面的代码所示:
push (@matches, ), while ($str =~ /([\*\!:;])/);
$str =~ s/([\*\!:;])//g;
是否可以在 Perl 中将其合并为一个步骤,在该步骤中全局进行替换,同时密切关注被替换的匹配项?
使用:
my $str = "An example: sentence!*";
my @matches = $str =~ /([\*\!:;])/g;
say Dumper \@matches;
$str =~ tr/*!:;//d;
输出:
$VAR1 = [
':',
'!',
'*'
];
尝试:
my $str = "An example: sentence!*";
push(@mys, ($str=~m/([^\w\s])/g));
print join "\n", @mys;
谢谢。
是的,有可能。
my @matches;
$str =~ s/[*!:;]/ push @matches, $&; "" /eg;
但是,我不相信上面的比下面的更快或更清晰:
my @matches = $str =~ /[*!:;]/g;
$str =~ tr/*!:;//d;
您可以在正则表达式中嵌入代码 运行:
my @matches;
my $str = 'An example: sentence!*';
$str =~ s/([\*\!:;])(?{push @matches, })//g;
但是对于这么简单的匹配,我只是分别进行捕获和替换。
这是您要找的吗?
my ($str, @matches) = ("An example: sentence!*");
#first method :
($str =~ s/([\*\!:;])//g) && push(@matches, );
#second method :
push(@matches, ) while ($str =~ s/([\*\!:;])//g);
我意识到可以通过一些小的变通方法来实现这一点,但我希望有更简单的方法(因为我经常使用这种类型的表达式)。
给定示例字符串:
my $str = "An example: sentence!*"
可以使用正则表达式来匹配每个标点符号并将它们捕获到一个数组中。 此后,我可以简单地重复正则表达式并替换匹配项,如下面的代码所示:
push (@matches, ), while ($str =~ /([\*\!:;])/);
$str =~ s/([\*\!:;])//g;
是否可以在 Perl 中将其合并为一个步骤,在该步骤中全局进行替换,同时密切关注被替换的匹配项?
使用:
my $str = "An example: sentence!*";
my @matches = $str =~ /([\*\!:;])/g;
say Dumper \@matches;
$str =~ tr/*!:;//d;
输出:
$VAR1 = [
':',
'!',
'*'
];
尝试:
my $str = "An example: sentence!*";
push(@mys, ($str=~m/([^\w\s])/g));
print join "\n", @mys;
谢谢。
是的,有可能。
my @matches;
$str =~ s/[*!:;]/ push @matches, $&; "" /eg;
但是,我不相信上面的比下面的更快或更清晰:
my @matches = $str =~ /[*!:;]/g;
$str =~ tr/*!:;//d;
您可以在正则表达式中嵌入代码 运行:
my @matches;
my $str = 'An example: sentence!*';
$str =~ s/([\*\!:;])(?{push @matches, })//g;
但是对于这么简单的匹配,我只是分别进行捕获和替换。
这是您要找的吗?
my ($str, @matches) = ("An example: sentence!*");
#first method :
($str =~ s/([\*\!:;])//g) && push(@matches, );
#second method :
push(@matches, ) while ($str =~ s/([\*\!:;])//g);