这里是一个新手问题。我有一个非常简单的 Perl 脚本,我希望正则表达式可以匹配字符串中的多个部分。
my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
print "$x\n";
}
这并不按照我想要的方式工作,因为它只返回ohai。我希望它能够匹配并输出ohai ther ohai。
我该如何解决此问题。
谢谢
这样做能实现你想要的吗?
my $string = "ohai there. ohai";
while ($string =~ m/(\w\w\w\w)/g) {
print "$1\n";
}
它返回
ohai
ther
ohai
来自perlretut:
修饰符"//g"代表全局匹配,允许匹配操作符尽可能多地在一个字符串内进行匹配。
此外,如果您想把匹配结果放入数组中,可以这样做:
my $string = "ohai there. ohai";
my @matches = ($string =~ m/(\w\w\w\w)/g);
foreach my $x (@matches) {
print "$x\n";
}
或者你可以这样做
my $string = "ohai there. ohai";
my @matches = split(/\s/, $string);
foreach my $x (@matches) {
print "$x\n";
}
ohai
there.
ohai
g
修饰符。 - Spudley