简体   繁体   中英

Return next line (next string) after a regex pattern was matched? (Python)

What I am trying to do is a pretty standard task of matching a particular result in a .HTML file. For this I am using python and wrote this code:

...

import re, requests

res = requests.get('http://www.website.com/page.html')

t = res.text

g = re.search("(regex)", t)

...

This works fine. However, my actual task is to get the string, which follows the string found by my regular expression. It is always in the following line of the .html-document. It is the whole line from start to finish, which probably makes it a little bit easier. Very unfortunately I have no way to find the right data directly with a regex.

What would be the most efficient way to achieve this?

One simple solution would be to iterate over the lines.

When a line matches, returns the next one:

import re

text = """abc
def
ghi
klm
"""

pattern = re.compile('def')

def find_following_line(text):
    lines = text.splitlines()
    for i, line in enumerate(lines):
        if re.search(pattern, line):
            return lines[i+1]

print(find_following_line(text))
# ghi

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