Perl如何删除字符串的第二行

时间:2015-09-25 13:21:04

标签: regex perl

Perl如何删除字符串的第二行?

我可以使用以下代码删除第一行:

$cpusttp =~ s/^(.*\n){1}//;

2 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点:

my $multi_line_string = 'line1
line2
line3
line 4
fifth line';

#regex matches once - second line is the first thing after a linefeed
#\n so it'll remove the second line. 
#This wouldn't scale well to removing the 4th line though. 
my ($new_string) = $multi_line_string =~ s/\n(.*\n)/\n/r;
print $new_string;

或者也许:

my @things = split ( "\n", $multi_line_string );
print join ("\n", @things[0,2..$#things] );

或者使用拼接:

my $line_to_delete = 1; #arrays start at 0
my @things = split ( "\n", $multi_line_string );
splice ( @things, $line_to_delete, 1);
print join ( "\n", @things);

答案 1 :(得分:2)

您不需要{1}。除非另有说明,否则任何内容都将重复一次。

另外,我认为正则表达式不适合这项工作。但是,这应该做:

$cpusttp =~ s/^(.*\n)\K(.*\n)//;

想法是匹配第一行,然后忽略它(\K),然后匹配另一行。