Perl/regex to remove first 3 lines and last 3 lines of a string

谁说胖子不能爱 提交于 2019-12-04 05:56:56

The previously given solutions are really complex! All one needs is

s/^(?:.*\n){1,3}//;
s/(?:.*\n){1,3}\z//;

If you want to accept a lack of trailing newline at the end, you can use

s/\n?\z/\n/;
s/^(?:.*\n){1,3}//;
s/(?:.*\n){1,3}\z//;

or

s/^(?:.*\n){1,3}//;
s/(?:.*\n){0,2}.*\n?\z//;

This should do the trick. You may need to replace "\n" with "\r\n" depending on the newline format of your input string. This will work regardless if the last line is terminated with newline or not.

$input = '1
2
3
a
b
c
d
e
4
5
6';

$input =~ /^(?:.*\n){3} ((?:.*\n)*) (?:.*\n){2}(?:.+\n?|\n)$/x;

$output = $1;

print $output

Output:

a
b
c
d
e
Ed Heal
for($teststring)
{
    s/<.*?>//g;
    $teststring =~ s%^(.*[\n\r]+){3}([.\n\r]).([\n\r]+){3}$%$2%;
    print "Outputstring" . "\n" . $teststring . "\n";
}

You need to test if it's under 6 lines, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!