Search code examples
regexp-replace

REGEX strategy to replace line breaks inside group


I'm trying to make a replacement in one pass with just one Regular expression but I think this is not possible at all. I'm using RegexBuddy but I'm always getting a catastrophic result and the expression cannot be evaluated.

For this text:

3 bla bla! !

4 yep yep! ?

FROM HERE

5 something randdom here!

6 perhaps some HTML there

TO HERE

7 what ever you like over here

8 and that's all folks!enter code here

I want to find a REGEX that replaces the line breaks by something else, let's say $$, but only on the section "from here" "to here". So basically the end result would be this:

3 bla bla! !

4 yep yep! ?

FROM HERE$$
$$
5 something randdom here!$$
$$
6 perhaps some HTML there$$
$$
TO HERE

7 what ever you like over here

8 and that's all folks!

I have this expression

((FROM HERE))((.*)(\n))+(TO HERE)

But I'm stuck so far trying to replace just the \n group by something else. I have done similar things in the past so I would say this should be possible in one go.

If this is not possible in regex I would simply create a C# console app to take first that text to a string and then replace each \n by $$, then put it back. That shouldn't be that difficult.


Solution

  • If you are using .NET, one option could be

    (?s)(?<=^FROM HERE\b.*?)\r?\n\r?\n(?=.*?^TO HERE\b)
    
    • (?s) Inline modifier, dot matches a newline
    • (?<=^FROM HERE\b.*?) Assert FROM HERE at the left at the start of the line
    • \r?\n\r?\n Match 2 newlines
    • (?=.*?^TO HERE\b) Assert TO HERE at the right at the start of the line

    In the replacement use (with double escapes $$)

    \n$$$$\n
    

    See a .NET regex demo and a C# demo.