简体   繁体   中英

regex match for each line

I need to match all of the lines that start with the regular expression. Sample input.

 #X0 alpha numeric content that  I want
 #X1 something else 
 #X26 this one as well

Both of these regular expression work but for the first line. I need to match against all of the #X\\d{1,2} lines.

     /^(\#X\d{1,2}\s+)(.*?)$/m
     /^(\#X\d{1,2}\s+)(.+)*$/m

What I get with any of the regex above.

   $pattern=  "/^(\#X\d{1,2}\s+)(.+)*$/m";
   preg_match($pattern, $content, $match);
   echo $match[1]; 
   alpha numeric content that  I want

Desired output.

   alpha numeric content that  I want
   something else 
   this one as well

Use preg_match_all with PREG_SET_ORDER flag. For example:

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

UPDATE

corresponding to the edited question.

preg_match_all('/^(\#X\d{1,2}\s+)(.*)/m', $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    echo $match[2] . "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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