Noob問題在這裏。我有一個非常簡單的Perl腳本,我想正則表達式的字符串用Perl匹配正則表達式多次
my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
print "$x\n";
}
在匹配多個零件這不是工作,我想因爲它只返回ohai的方式。我想它匹配並打印出ohai ther ohai
我該如何去做這件事。
謝謝
Noob問題在這裏。我有一個非常簡單的Perl腳本,我想正則表達式的字符串用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
好的建議,但在這裏分裂將返回「那裏。」帶點。最好做一個「split(/ \ W + /,$ string)」來獲取單詞。 – 2014-09-05 08:23:22
+1。正確答案。你需要在你的正則表達式的末尾使用'g'修飾符。 – Spudley 2011-06-16 16:00:48
謝謝!我想我需要更仔細地看待這個文檔/ g – 2011-06-16 16:03:48
注意在「foreach」中,「print $ 1」只會在每次出現模式匹配時打印最後一個「Ohai」是有用的(即3次)。因此,「while」似乎是您擁有多種元素的圖案時的最佳選擇。 – 2014-09-05 08:20:50