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

I wanted to create a regex statement to always delete the first 3 lines of a line and the last 3 lines of a line (the middle part can be any number of n lines). Any pure regular expression this way out? (i.e. always split our first 3 lines and the last 3 lines of a line - and save the middle part, which can be a variable of # lines)

Thanks.

eg.

Input line:

" 1 2 3 <1...n # of lines content> 4 5 6 " 

To the desired output line:

 "<1..n # of lines content>" 
+6
source share
3 answers

Previously defined solutions are really complicated! All you need is

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

If you want to accept the flaw of the 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//; 
+8
source

That 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 whether the last line ends with a new line 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 

Conclusion:

 a b c d e 
+4
source
 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 is under 6 lines, etc.

-1
source

Source: https://habr.com/ru/post/894950/


All Articles