使用Perl多次匹配正则表达式

12

这里是一个新手问题。我有一个非常简单的 Perl 脚本,我希望正则表达式可以匹配字符串中的多个部分。

my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
    print "$x\n";
}

这并不按照我想要的方式工作,因为它只返回ohai。我希望它能够匹配并输出ohai ther ohai

我该如何解决此问题。

谢谢

2个回答

30

这样做能实现你想要的吗?

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";
}    

2
+1。正确答案。你需要在正则表达式的末尾加上 g 修饰符。 - Spudley
2
谢谢!我想我需要更仔细地查看文档中的/g。 - Collin O'Connor
值得注意的是,在“foreach”中,“print $1”只会打印每次模式匹配(即3次)中最后一个“Ohai”。因此,当您的模式具有多个元素时,“while”似乎是最好的选择。 - Jean-Francois T.

0

或者你可以这样做

my $string = "ohai there. ohai";
my @matches = split(/\s/, $string);
foreach my $x (@matches) {
  print "$x\n";
}   

在这种情况下,split函数按空格分割并打印。
ohai
there.
ohai

好的建议,但在这里分割会返回带有句点的“there”。最好使用“split(/\W+/, $string)”仅获取单词。 - Jean-Francois T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接