jbcedge
jbcedge

Reputation: 19505

replacing the dot with <br /> using regex in perl

I am using this example:

New Zealand cyclist Jack Bauer didn't know it during the Olympic road race, but there was a scantily-clad Kiwi 'snow angel' above him. http://www.stuff.co.nz/sport/olympics/7374497/Near-naked-snow-angel-over-cycle-road-race

I want to add a <br /> tag after the full stop but not in HTTP link. Just at the end of the sentence.

Currently I am using :

$full_story = $read_story->[0]{story_text}; 
$full_story =~ s/(\D)\.(\D)/<br \/><br \/>/i;

Using this code it adds the <br /> but the m from him is being removed.

Final Result:

New Zealand cyclist Jack Bauer didn't know it during the Olympic road race, but there was a scantily-clad Kiwi 'snow angel' above him.

http://www.stuff.co.nz/sport/olympics/7374497/Near-naked-snow-angel-over-cycle-road-race

What am I doing wrong?

Upvotes: 0

Views: 3428

Answers (3)

the_qbf
the_qbf

Reputation: 368

You could do a search and replace 's///'

given the string:

my $string = 'The quick brown fox. Jumps over the lazy dog.';

you could do:

$string =~ s/\./<br \/>/g

the 's' means you're doing a search and replace.

Between the first two '/ /' is the one you're searching for. In this case it's a dot (.) but you have to escape it with \ since dot in regex is a wild card.

Between the next '/ /' is the text you're trying to replace. In this case it's <br />. again you have to escape '/' in here since it's a special character.

Lastly, the 'g' flag at the end means your searching and replacing in the whole string. So in my example the output would be:

print $string;
# The quick brown fox<br /> Jumps over the lazy dog<br />

Since you don't want to replace the dots in the string, you could simple separate them in different variables so that it will be easier to manipulate.

Upvotes: 3

Borodin
Borodin

Reputation: 126722

Use index to establish the length of the first part of the string up to any http link. Then use substr as an lvalue to replace all full-stops in just that part.

This code shows the idea. I have added a couple of extra full-stops for testing purposes.

use strict;
use warnings;

my $str = q{New Zealand cyclist Jack Bauer. didn't know it during the Olympic. road race, but there was a scantily-clad Kiwi 'snow angel' above him.http://www.stuff.co.nz/sport/olympics/7374497/Near-naked-snow-angel-over-cycle-road-race};

my $index = index lc $str, 'http';
$index = length $str if $index < 0;
substr($str, 0, $index) =~ s|\.|.<br/>\n<br/>\n|g;

print $str;

output

New Zealand cyclist Jack Bauer.<br/>
<br/>
 didn't know it during the Olympic.<br/>
<br/>
 road race, but there was a scantily-clad Kiwi 'snow angel' above him.<br/>
<br/>
http://www.stuff.co.nz/sport/olympics/7374497/Near-naked-snow-angel-over-cycle-road-race

Upvotes: 0

Andrew Cheong
Andrew Cheong

Reputation: 30273

$full_story =~ s/(.*?)\.(.*?)/$1<br \/><br \/>$2/i;

Upvotes: 0

Related Questions