简体   繁体   中英

Get the line above the matched regex expression in Python

I want to extract the line above the regex matched expression.

Text 1
28-Apr
Text2
Text3
29-Apr

Output: ['Text 1', 'Text3']

To do that, you need to find the line numbers when your pattern occurs and then get the lines above, by subtracting 1 from the line numbers that were found. For example, if your pattern occurs on line 2 and 4, you need to get line 1 and 3. Please, look the example code below:

import re

string = """Text 1
28-Apr
Text2
Text3
29-Apr"""





pattern = '\d*\-\w*'
lines_number  = []
for m in re.finditer(pattern, string):
    start = m.start()
    lineno = string.count('\n', 0, start)


    lines_number.append(lineno)

for l in lines_number:
    print(string.split('\n')[l-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM