[英]How can I find all matches to a regular expression in Perl?
我的表格中有文字:
Name=Value1
Name=Value2
Name=Value3
使用Perl,我想在每次出现时匹配/Name=(.+?)/
并提取(。+?)并将其推送到数组。 我知道我可以使用$1
来获取我需要的文本,我可以使用=~
来执行正则表达式匹配,但我不知道如何获得所有匹配。
列表上下文中的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";
但是,您似乎正在解析INI样式配置文件。 在这种情况下,我会推荐Config :: Std 。
my @values;
while(<DATA>){
chomp;
push @values, /Name=(.+?)$/;
}
print join " " => @values,"\n";
__DATA__
Name=Value1
Name=Value2
Name=Value3
以下将给出数组中正则表达式的所有匹配项。
push (@matches,$&) while($string =~ /=(.+)$/g );
使用Config::
module读取配置数据。 对于像这样简单的东西,我可能会找到ConfigReader :: Simple 。 尽可能地远离杂草是件好事。
而不是使用正则表达式,您可能更喜欢尝试语法引擎,如:
在SO之前,我已经给出了一个Parse :: ResDescent答案的片段。 然而Regexp :: Grammars看起来非常有趣,受Perl6规则和语法的影响 。
所以我以为我在Regexp :: Grammars上有一个裂缝;-)
use strict;
use warnings;
use 5.010;
my $text = q{
Name=Value1
Name = Value2
Name=Value3
};
my $grammar = do {
use Regexp::Grammars;
qr{
<[VariableDeclare]>*
<rule: VariableDeclare>
<Var> \= <Value>
<token: Var> Name
<rule: Value> <MATCH= ([\w]+) >
}xms;
};
if ( $text =~ $grammar ) {
my @Name_values = map { $_->{Value} } @{ $/{VariableDeclare} };
say "@Name_values";
}
上面的代码输出Value1 Value2 Value3
。
非常好! 唯一需要注意的是它需要Perl 5.10并且对于您提供的示例可能有点过分;-)
/ I3az /
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.