[英]Matching a regular expression multiple times with Perl
Noob問題在這里。 我有一個非常簡單的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.