简体   繁体   English

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

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

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. 我试图在Perl中提出一个正则表达式来匹配多个模式,并像PHP中的preg_match_all一样返回所有模式。

Here's what I have: 这是我所拥有的:

$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'. 我希望能够匹配所有出现的指定模式:“测试”,“数据”和“字符串”。

I know that in PHP, you can use preg_match_all for this kind of purpose: 我知道在PHP中,您可以将preg_match_all用于这种目的:

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

The above PHP code would match all 3 strings: 'test', 'data' and 'string'. 上面的PHP代码将匹配所有3个字符串:“ test”,“ data”和“ string”。

I want to know how to do this in Perl. 我想知道如何在Perl中做到这一点。 Any help would be greatly appreciated. 任何帮助将不胜感激。

The Perl equivalent to Perl相当于

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

is

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

The /g flag stands for global, so it returns a list of matches in list context. / g标志代表全局,因此它在列表上下文中返回匹配列表。

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

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

Note the /g 注意/ g

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

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