我需要匹配以正则表达式开头的所有行。样本输入。
#X0 alpha numeric content that I want
#X1 something else
#X26 this one as well
这两个正则表达式都适用于第一行。我需要匹配所有#X \ d {1,2}行。
/^(\#X\d{1,2}\s+)(.*?)$/m
/^(\#X\d{1,2}\s+)(.+)*$/m
我从上面的任何正则表达式中获得了什么。
$pattern= "/^(\#X\d{1,2}\s+)(.+)*$/m";
preg_match($pattern, $content, $match);
echo $match[1];
alpha numeric content that I want
期望的输出。
alpha numeric content that I want
something else
this one as well
答案 0 :(得分:2)
将preg_match_all与PREG_SET_ORDER
标志一起使用。例如:
$text = <<<EOT
#X0 alpha numeric content that I want
#X1 something else
#X26 this one as well
EOT;
preg_match_all('/^(\#X\d{1,2}\s+)(.*)/m', $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[0] . "\n";
}
<强>更新强>
对应编辑的问题。
preg_match_all('/^(\#X\d{1,2}\s+)(.*)/m', $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[2] . "\n";
}