Home > other >  get last two line regex
get last two line regex

Time:03-24

I want to get last two line of a multilines text.

Lorem ipsum dolor sit amet, 
Praesent libero. Sed cursus ante 
dapibus diam. Sed nisi. Nulla  
imperdiet. Duis sagittis ipsum.

I would get :

dapibus diam. Sed nisi. Nulla  
imperdiet. Duis sagittis ipsum.

CodePudding user response:

You could use the following regex pattern, with multiline mode turned off:

(?<=^|\n).*?\n.*$

Demo

This regex says to match:

(?<=^|\n)  assert that what precedes is either the end of a previous line
           or the start of the text (for texts having only two lines)
.*?\n      match the second to last line, followed by newline
.*$        match the last line until the end

Here is a sample Python script, which uses a slightly modified regex:

import re

inp = """Lorem ipsum dolor sit amet, 
Praesent libero. Sed cursus ante 
dapibus diam. Sed nisi. Nulla  
imperdiet. Duis sagittis ipsum."""

output = re.search(r'(?:^|\n)(.*?\n.*)$', inp)
print(output.group(1))

CodePudding user response:

I am not sure with what technology you are trying to achieve, but May be my Logic may help you..

/* Read / open the File*/
$fileObj = file("yourfile.txt");

/* Read / open the File*/
for ($i = max(0, count($fileObj)-2); $i < count($fileObj); $i  ) {
  echo $fileObj[$i] . "\n";
}

Otherwise you can use the array_slice method.

$all_lines = file('yourfile.txt');
$last_2 = array_slice($all_lines , -2);

CodePudding user response:

Non-regex way to solve in python:

>>> print (text)
Lorem ipsum dolor sit amet, 
Praesent libero. Sed cursus ante 
dapibus diam. Sed nisi. Nulla  
imperdiet. Duis sagittis ipsum.
>>> 
>>> print('\n'.join(text.splitlines()[-2:]))
dapibus diam. Sed nisi. Nulla  
imperdiet. Duis sagittis ipsum.

Use built-in splitlines method on the input string, slice out the last two elements, then join together with a newline.

  • Related