Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match n number of lines with regex

Tags:

java

regex

I have some text like this

Notes:
He jumped the sea-horse
but it looked ropey
Then he left

but sometimes its like this

Notes:




Clay is only green
When it is seen

I need to capture 4 lines of text after "Notes" only so the output should be

Notes:
He jumped the sea-horse
but it looked ropey
Then he left

and for the second example

Notes:

I have tried matching the newlines but it only matches after the rest of the regex

Notes:.*\n{4}

How can I create a regex that allows me to repeat the match for the whole line and a newline four times? (is this a non-capturing group??)

like image 628
Sebastian Zeki Avatar asked Jan 24 '26 09:01

Sebastian Zeki


1 Answers

You were close - in Notes:.*\n{4} the {4} is binding only to the newline, so it'll only capture "Notes:" followed by anything, followed by 4 blank lines.

You're looking for something like Notes:\n((?:.*\n){1,4})

like image 197
Andrew Rueckert Avatar answered Jan 26 '26 23:01

Andrew Rueckert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!