0

我正在使用这个例子:

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

我想在<br />句号之后添加一个标签,但不在 HTTP 链接中。就在句末。

目前我正在使用:

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

使用此代码,它添加了<br />mfromhim正在被删除。

最后结果:

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

我究竟做错了什么?

4

3 回答 3

3

您可以进行搜索并替换 's///'

给定字符串:

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

你可以这样做:

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

's' 表示您正在进行搜索和替换。

前两个 '/ /' 之间是您要搜索的那个。在这种情况下,它是一个点 (.),但您必须使用 \ 对其进行转义,因为正则表达式中的点是通配符。

在下一个“/ /”之间是您要替换的文本。在这种情况下,它是<br />. 再次,您必须在这里转义“/”,因为它是一个特殊字符。

最后,末尾的“g”标志表示您在整个字符串中进行搜索和替换。所以在我的例子中,输出将是:

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

由于您不想替换字符串中的点,您可以简单地将它们分隔在不同的变量中,以便更容易操作。

于 2012-10-23T15:32:36.760 回答
0

用于index建立到任何http链接的字符串的第一部分的长度。然后substr用作左值来替换该部分中的所有句号。

这段代码显示了这个想法。为了测试目的,我添加了几个额外的句号。

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;

输出

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
于 2012-08-16T22:14:29.303 回答
0
$full_story =~ s/(.*?)\.(.*?)/$1<br \/><br \/>$2/i;
于 2012-08-16T21:30:02.170 回答