Regex: match all until newlines appear after a space

I have this example:

This is a simple test text. Yet another line. START: This is the part that needs match. This part does not need capture. Wherever else text. 

I want to combine this part:

 START: This is the part that needs capture. 

The point is that I know that START: is, and ends with a new line that has something other than a space.

I have tried many combinations starting with: START: (.*?)

I talked to \ r and all I could think was to fit only if it didn't have white space.

I'm not sorry because I'm lazy. I spent several hours before asking.

+4
source share
2 answers

How about this:

 preg_match( '/^ # Start of line START:\ # Match "START: " .* # Match any characters except newline \r?\n # Match newline (?: # Try to match... ^ # from the start of the line: \ + # - one or more spaces .* # - any characters except newline \r?\n # - newline )* # Repeat as needed/mx', $subject) 

This assumes that all lines end with a newline.

+9
source

This code will work correctly with your sample test.

A workaround is a token that replaces new lines before preg_match (which are restored after!) And the Ungreedy modifier at the end of regex (U)

 <?php $token = '#####'; $text = <<<TXT This is a simple test text. Yet another line. START: This is the part that needs match. This part does not need capture. Wherever else text. TXT; $text = str_replace("\n", $token, $text); if (preg_match('/(?P<match>START:(.)*)(' . $token . '){1}[^ ]+/Uu', $text, $matches)) { $match = str_replace($token, "\n", $matches['match']); var_dump($match); } $text = str_replace($token, "\n", $text); 

The output will be:

 string(42) "START: This is the part that needs match." 
+1
source

Source: https://habr.com/ru/post/1436530/


All Articles