searching for last group of text between specific characters

Viewed 39

I have a text file that has data printed in the following way

---
1A
1B
1C
---
---
2A
2B
2C
---
---
3A
3B
3C
.
.
3n
---
NA
.
.
Nn
---

essentially lines of text encased around lines of --- to ---.

I am looking to extract the contents between the last occurrence of --- to ---, so far using regex I have have managed to narrow it down to (?<=---)(.*?)(?=---) however this finds all occurrences and I would only like the last.

1 Answers

If you match the string with the regular expression

r'(?s).*^---\r?\n(.*)(?=^---)'

capture group 1 will contain the string of interest.

Demo

Python's regex engine performs the following operations.

(?s)        set single-line mode so that '.' matches newlines
.*          match 0+ characters (greedily)
^---\r?\n   match line '---'
(.*)        match 0+ characters in capture group 1
(?=^---)    match '---' at beginning of line in positive lookahead

The first .*, being greedy, gobbles up characters, including newlines and hyphens, until it has consumed the line '---' that is followed later in the string by one more line '---'. It cannot go beyond the penultimate line '---' because it it were to do so it would have to consume the last '---' line, yet the match must be followed by the last '---' line.

Related