How can I do a global regular expression match in Perl?
我试图在Perl中提出一个正则表达式来匹配多个模式,并像PHP中的
这就是我所拥有的:
1 2 3 4 5 6 7 8 9 10 11 | $str = 'testdatastring'; if($str =~ /(test|data|string)/) { print"its found index location: $0 $-[0]-$+[0]\ "; print"its found index location: $1 $-[1]-$+[1]\ "; print"its found index location: $2 $-[2]-$+[2]\ "; print"its found index location: $3 $-[3]-$+[3]\ "; } |
这只给了我第一个匹配,即"测试"。我希望能够匹配所有出现的指定模式:"测试","数据"和"字符串"。
我知道在PHP中,您可以将preg_match_all用于以下目的:
1 2 3 |
上面的PHP代码将匹配所有3个字符串:" test"," data"和" string"。
我想知道如何在Perl中做到这一点。任何帮助将不胜感激。
相当于
的Perl
1 |
是
1 | @m = ("testdatastring" =~ m/(test|data|string)/g); |
/ g标志代表全局,因此它在列表上下文中返回匹配列表。
请参阅http://www.anaesthetist.com/mnm/perl/regex.htm。基本语法(从那里开始)是:
1 2 | $_ ="alpha xbetay xgammay xdeltay so on"; ($first, $second, $third) = /x(.+?)y/g; |
注意/ g