php - 如何在 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 标志代表全局,因此它返回列表上下文中的匹配列表。

https://stackoverflow.com/questions/948795/

相关文章:

erlang - 如何获取erlang集群中的当前节点名称?

xml - 对齐 ="right"在 XML 中不起作用

oracle - 关闭 Oracle 中的索引

.net - 在运行时替换 .NET 类型

list - 如何找到列表列表中最长的列表?

oracle - 如何使用 pl/sql 循环接受用户输入?

vba - VBA 中的 "Dim fso, MyFile, FileName, TextLine"

css - 如何使用 Notepad++ 将 css long 转换为 css one line s

visual-studio - 如何显示 Win32 MessageBox?

perl - 我如何检查一个值是否在 Perl 的列表中?