http://www.perlmonks.org?node_id=1018136


in reply to Replace newlines only if not inside braces

As long as the braces groups are not nested you could do it by separating blocks in a split and handling them differently.
use Data::Dump; my $data = q| foo bar {{ alpha beta }} baz |; @splits = split /({{.*?}})/s, $data; dd \@splits; my $result=""; while (my $block = shift @splits) { $block =~ s/\n/<br>\n/gs; $result .= $block; $result .= shift @splits if @splits; } print $result;

output
["\nfoo\nbar\n", "{{\nalpha\nbeta\n}}", "\nbaz\n"] <br> foo<br> bar<br> {{ alpha beta }}<br> baz<br>

I refrain from trying a complicated and potentially unmaintainable one-line regex solution.

Some come to mind¹, but I don't see the necessity if there are no other restrictions (like lack of memory) involved.

Cheers Rolf

UPDATE
¹) like

Replies are listed 'Best First'.
Re^2: Replace newlines only if not inside braces
by jbryan (Acolyte) on Feb 11, 2013 at 21:24 UTC