如何在Perl中进行全局正则表达式匹配? [英] How can I do a global regular expression match in Perl?
问题描述
我试图在Perl中提出一个正则表达式来匹配多个模式,并像PHP中的preg_match_all
一样返回所有模式.
I am trying to come up with a regular expression in Perl matching multiple patterns and returning all of them like preg_match_all
in PHP does.
这就是我所拥有的:
$str = 'testdatastring';
if($str =~ /(test|data|string)/) {
print "its found index location: $0 $-[0]-$+[0]\n";
print "its found index location: $1 $-[1]-$+[1]\n";
print "its found index location: $2 $-[2]-$+[2]\n";
print "its found index location: $3 $-[3]-$+[3]\n";
}
这只给了我第一个匹配,即测试".我希望能够匹配所有出现的指定模式:测试",数据"和字符串".
This only gives me the first match which in this is 'test'. I want to be able to match all occurrences of specified patterns: 'test', 'data' and 'string'.
我知道在PHP中,您可以将preg_match_all用于此类目的:
I know that in PHP, you can use preg_match_all for this kind of purpose:
if(preg_match_all('/(test|data|string)/', 'testdatastring', $m)) {
echo var_export($m, true);
}
上面的PHP代码将匹配所有3个字符串:"test","data"和"string".
The above PHP code would match all 3 strings: 'test', 'data' and 'string'.
我想知道如何在Perl中做到这一点.任何帮助将不胜感激.
I want to know how to do this in Perl. Any help would be greatly appreciated.
推荐答案
Perl等效于
preg_match_all('/(test|data|string)/', 'testdatastring', $m)
是
@m = ("testdatastring" =~ m/(test|data|string)/g);
/g标志代表全局,因此它在列表上下文中返回匹配项列表.
The /g flag stands for global, so it returns a list of matches in list context.
这篇关于如何在Perl中进行全局正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!