Noob问题在这里.我有一个非常简单的perl脚本,我希望正则表达式匹配字符串中的多个部分
my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
print "$x\n";
}
Run Code Online (Sandbox Code Playgroud)
这不是我想要的方式,因为它只返回ohai.我希望它匹配并打印ohai ther ohai
我该怎么做呢?
谢谢
小智 28
这会做你想要的吗?
my $string = "ohai there. ohai";
while ($string =~ m/(\w\w\w\w)/g) {
print "$1\n";
}
Run Code Online (Sandbox Code Playgroud)
它回来了
ohai
ther
ohai
Run Code Online (Sandbox Code Playgroud)
来自perlretut:
修饰符"// g"代表全局匹配,并允许匹配运算符在字符串中尽可能多地匹配.
此外,如果您想将匹配放在数组中,您可以执行以下操作:
my $string = "ohai there. ohai";
my @matches = ($string =~ m/(\w\w\w\w)/g);
foreach my $x (@matches) {
print "$x\n";
}
Run Code Online (Sandbox Code Playgroud)