用eval替换并通过分组字符串长度重复该字符?

时间:2016-09-07 09:54:02

标签: regex perl

我的输入如下

my $s = '<B>Estimated:</B>

The N-terminal of the sequence considered is M (Met).

The estimated half-life is: 30 hours (mammalian reticulocytes, in vitro).
                        >20 hours (yeast, in vivo).
                        >10 hours (Escherichia coli, in vivo).


<B>Instability index:</B>

The instability index (II) is computed to be 31.98
This classifies the protein as stable.';

我想从字符串中删除<B></B>标记,并为粗体标记添加下划线。

我预计输出

Estimated:
---------
The N-terminal of the sequence considered is M (Met).

The estimated half-life is: 30 hours (mammalian reticulocytes, in vitro).
                        >20 hours (yeast, in vivo).
                        >10 hours (Escherichia coli, in vivo).


Instability index:
------------------
The instability index (II) is computed to be 31.98
This classifies the protein as stable.

为此尝试了以下正则表达式,但我不知道那里有什么问题。

$s=~s/<B>(.+?)<\/B>/"$1\n";"-" x length($1)/seg; # $1\n in not working

在上面的正则表达式中我不知道如何把这个"$1\n"?如何使用由;或其他任何东西分隔的替换中的连续语句?

我该如何解决?

1 个答案:

答案 0 :(得分:2)

e修饰符仅返回最后执行的语句,因此

$s=~s/<B>(.+?)<\/B>/"$1\\n";"-" x length($1)/seg;

抛弃"$1\\n"(应该是"$1\n"

这有效:

$s=~s/<B>(.+?)<\/B>/"$1\n" . "-" x length($1)/seg;

我询问您的Perl版本的原因是评估是否可以使用\K进行有效的可变长度后视:

$s=~s/<B>(.+?)<\/B>\K/ "\n" . "-" x length($1)/seg;

\K适用于Perl版本5.10 +。