$Data = <DATA>;
$Data =~ s/(\[NEW\].+?)\<?(\n\[)/$1<p>$2/sg;
This looks for a NEW block followed by something (. = match all chars, + = match 1 or more times). Next there may be a < (? = 0 or 1 matches) and then we expect a newline and a [ (beginning of the next OLD or NEW block).
The NEW block including "something" (which is all the text of this block) is put in ( ) which makes them accessible as $1, so is the last part (newline + [ ). They're merged with a <p>.
Finally, /s treats the whole data as a single line so that the .+ - match will also match newlines and the g repeates this replacement until there is no match left.
All this assumes Linux, for Windows newlines, add a \r before the \n.
If you got more data than you would like to keep and process in RAM, it's a little bit longer, you need to keep the last line before printing:
#!/usr/bin/perl
while(<DATA>){
if (/^(\[\w+\])/) { # New block starts
$line =~ s/\<$/<p>/
if $f eq 'NEW'; # Replace the < by <p> for NEW blocks only
$f = $1;
}
defined($line) and print $line; # Print the last line
$line = $_; # keep for next run # Save this line
}
print $line; # Print last line
__DATA__
[NEW]
Dear Carolyn: My husband and I divorced after 42 years. It didn't tak
+e long
for him to find a replacement, but I was happy for him at the time.<
them and let my grandchildren dig through her purse as if she were the
+ir
grandmother.<
[OLD]
This loops through your lines and remembers the current line.
If the current line is a ... block, the remembered line is modified as you requested: a <p> is added and the < is removed.
For the last step, the remembered and maybe modified line is being printed.
If you want the <p> only at NEW bondaries but also want to get rid of the < on every ... boundary, split the regexp:
$line =~ s/\<$//; # Remove <
$line .= '<p>' if $f eq 'NEW'; # Add <p> for NEW blocks only
(I didn't try this code myself, so there may be typos.) |