简体   繁体   中英

Regex match the first line after blank line

I want to check the first line after blank line I tried with ^$.* but not working,

YYYY-MM-DD HH:II:SS Message Log
Message Log

Message Log
not empty line

the desired output: ["YYYY-MM-DD HH:II:SS Message Log","Message Log"]

Not sure why are you using a Regex for this task, I think you can use a simple split .

data = '''YYYY-MM-DD HH:II:SS Message Log
Message Log

Message Log
not empty line'''

relevant_part, _ = data.split('\n\n', 1)
relevant_part.splitlines() # ["YYYY-MM-DD HH:II:SS Message Log","Message Log"]

You could use:

import re


pattern = re.compile("(?:^|\n\n)(.*)")
pattern.findall(data)

OUTPUT

['YYYY-MM-DD HH:II:SS Message Log', 'Message Log']

To test it, I have saved these lines in a file:

YYYY-MM-DD HH:II:SS Message Log
Message Log

Message Log
not empty line

read the content in data and applied the pattern to it.

Your regex fails because you don't match the newline character.

Also .* will match a blank line, so use .+ .

Try

regex = r"(?<=^\n).+"

print(re.search(regex, text, re.MULTILINE).group(0))

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