【问题标题】:regex match for each line每行的正则表达式匹配
【发布时间】:2013-08-03 04:25:40
【问题描述】:

我需要匹配所有以正则表达式开头的行。示例输入。

 #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

【问题讨论】:

  • 抱歉,不清楚您在问什么。你能详细说明一下吗?此外,不清楚为什么第二个正则表达式是相关的,因为它涉及以“#O”开头的行,这在您的示例中不存在。

标签: php regex


【解决方案1】:

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

【讨论】:

  • 最后一个子模式最好使用.*而不是.*?,因为$不包含在.的含义中。
  • @Kolink,谢谢你的建议。我更新了代码。我也删除了$
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多