Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: match everything until a new lines comes without space after it

Tags:

regex

php

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 match this part:

START: This is the part that
     needs capture.

The point is I know the START: is there and it ends with a new line that has anything but a space after it.

I have tried a lot of combinations starting from: START: (.*?)

I have plaid around with \r and anything I could think of to match only if it has no white-space.

I am not a noob asking because I am lazy. I spent a few hours before asking.

like image 955
transilvlad Avatar asked Dec 11 '22 22:12

transilvlad


1 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 are newline-terminated.

like image 147
Tim Pietzcker Avatar answered Apr 20 '23 00:04

Tim Pietzcker