繁体   English   中英

如何在Perl中进行全局正则表达式匹配?

[英]How can I do a global regular expression match in Perl?

我试图在Perl中提出一个正则表达式来匹配多个模式,并像PHP中的preg_match_all一样返回所有模式。

这是我所拥有的:

$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";
}

这只给了我第一个比赛“测试”。 我希望能够匹配所有出现的指定模式:“测试”,“数据”和“字符串”。

我知道在PHP中,您可以将preg_match_all用于这种目的:

if(preg_match_all('/(test|data|string)/', 'testdatastring', $m)) {
        echo var_export($m, true);
}

上面的PHP代码将匹配所有3个字符串:“ test”,“ data”和“ string”。

我想知道如何在Perl中做到这一点。 任何帮助将不胜感激。

Perl相当于

preg_match_all('/(test|data|string)/', 'testdatastring', $m)

@m = ("testdatastring" =~ m/(test|data|string)/g);

/ g标志代表全局,因此它在列表上下文中返回匹配列表。

参见http://www.anaesthetist.com/mnm/perl/regex.htm 基本语法(从那里开始)是:

$_ = "alpha xbetay xgammay xdeltay so on";
($first, $second, $third) = /x(.+?)y/g;

注意/ g

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM