cyberdog cyberdog - 3 months ago 18
Vb.net Question

Regex: Matching only groups that have a specific word embedded

I cannot figure out how to match only on groups that contain a certain word ('test' for example below). It is a big text file and the groups start with a line 'Group x' and include text with an empty line separation to the next group. I think I need to use lookaheads and lookbehinds but don't know how. I can use vb.net for this but trying to test out different expressions in the regex testers and can't get anywhere.

Group 1
adfdf
dd test ddfdf
dfdfadf

Group 2
ddfadfa

Group 3
add test
adfdff

Group 4
adfdf


Expected 2 matches:

Group 1
adfdf
dd test ddfdf
dfdfadf

Group 3
add test
adfdff

Answer

Start your pattern with ^Group \d+$ and end with ^$. In the middle match test but not preceeded by an empty line $(?:.(?!^$) (see Regular expression to match line that doesn't contain a word? for details on how the latter works). Don't forget the m and s modifiers:

^Group \d+$(?:.(?!^$))*?test.*?^$

Demo: https://regex101.com/r/kM9qB3/1