【问题标题】:How can I do a global regular expression match in Perl?如何在 Perl 中进行全局正则表达式匹配?
【发布时间】:2010-10-31 05:34:22
【问题描述】:

我正在尝试在 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";
}

这只会给我第一个匹配项,即“测试”。我希望能够匹配所有出现的指定模式:'test'、'data' 和 'string'。

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

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

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

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

【问题讨论】:

    标签: php regex perl preg-match-all


    【解决方案1】:

    Perl 等价于

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

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

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

    【讨论】:

    • 如何在 if/else 语句中应用它?
    • 解决了: if (@list = $str =~ Regex){True}{False} 使用 /regex/g 将找到的项目分组到列表中。
    【解决方案2】:

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

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

    注意 /g

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多