TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16359

Match a block of text enclosed by newlines that contains a pattern

Given the text:



text text 
texttexttext text BOB
text


text
texttt text
text


text text text 
tBOBext
texttexttext text
text 
text


text text text 
text
texttexttext text
text


What would be the reggex that would match:


text text 
texttexttext text BOB
text

and


text text text 
tBOBext
texttexttext text
text 
text

Am taking it step by step first trying to identify a pattern for matching any block of text surrounded by a newline on both sides. Am hoping to add the BOB filter after that.

I'm currently at ^\n(\n|.)*?^$. It doesn't match the ending newline, and also has matches on empty lines without any text.

Reggex editor with this example

Upvotes: 1

Views: 346

Answers (1)

anubhava
anubhava

Reputation: 785721

You may use this regex:

^(?:.+\R)*^.*?BOB.*\R(?:^.+\R)*

Updated RegEx Demo

RegEx Details:

  • ^: Match start
  • (?:.+\R)*: Match 0 or more lines with at least 1 character
  • ^.*?BOB.*\R: Match a line with BOB somewhere
  • (?:^.+\R)*: Match 0 or more lines with at least 1 character

regexp img


If you are fine with lookahead then you may also use this regex:

^(?=(?:.+\R)*.*?BOB)(?:.+\R)+

RegEx Demo 2

Upvotes: 2

Related Questions