Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Replace newlines only if not inside braces

by LanX (Canon)
on Feb 11, 2013 at 13:25 UTC ( #1018136=note: print w/ replies, xml ) Need Help??


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
  • looping with while (/({{.*?}})/gs) (and \G and pos)
  • using /e to do substitution within substitutions
  • complicated look-ahead and look-behind assertion
  • using \K somehow to restrict replacement


Comment on Re: Replace newlines only if not inside braces
Select or Download Code
Re^2: Replace newlines only if not inside braces
by jbryan (Acolyte) on Feb 11, 2013 at 21:24 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1018136]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2015-07-04 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls