如何在Perl中找到正则表达式的所有匹配项?

Tho*_*ens 21 regex perl

我的表格中有文字:

Name=Value1
Name=Value2
Name=Value3
Run Code Online (Sandbox Code Playgroud)

使用Perl,我希望/Name=(.+?)/每次出现时都匹配并提取(.+?)并将其推送到数组上.我知道我可以$1用来获取我需要的文本,我可以=~用来执行正则表达式匹配,但我不知道如何获得所有匹配.

Sin*_*nür 47

一个m//g在列表环境将返回所有拍摄比赛.

#!/usr/bin/perl

use strict; use warnings;

my $str = <<EO_STR;
Name=Value1
Name=Value2
Name=Value3
EO_STR

my @matches = $str =~ /=(\w+)/g;
# or my @matches = $str =~ /=([^\n]+)/g;
# or my @matches = $str =~ /=(.+)$/mg;
# depending on what you want to capture

print "@matches\n";
Run Code Online (Sandbox Code Playgroud)

但是,您似乎正在解析INI样式配置文件.在这种情况下,我会推荐Config :: Std.

  • 需要注意的重要事项是正则表达式末尾的`g`. (6认同)

aar*_*ist 6

my @values;
while(<DATA>){
  chomp;
  push @values, /Name=(.+?)$/;
}   
print join " " => @values,"\n";

__DATA__
Name=Value1
Name=Value2
Name=Value3
Run Code Online (Sandbox Code Playgroud)

  • 如果正则表达式没有成功,请不要使用$ 1:`/Name=(.+?)$/并推送@values,$ 1`.甚至只是`我的@values = map /Name=(.+?)$/, <DATA>;` (5认同)

小智 5

以下将给出数组中正则表达式的所有匹配项。

push (@matches,$&) while($string =~ /=(.+)$/g );
Run Code Online (Sandbox Code Playgroud)