Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Multiline Match End of String

I'm trying to match until I hit a pattern("this" ignoring any white spaces between start of line and pattern) or until the end of a string in a paragraph by using:

r'.*?(?=^[^\S\n]*this|$)'

This regex string works fine if my string is only one line($ matches an end of line). However I could not find the regex to match a end of string, so is there a clean way around this? The following is my code:

import re  
a_str="""\  
paragraph starts here  
another line
this line may or may not exist"""  
a_match = re.compile(r'.*?(?=^[^\S\n]*this|$)', re.MULTILINE|re.DOTALL).match(a_str)

EDIT:

Expected output:

"paragraph starts here\nanother line"
like image 201
Henry Avatar asked Sep 06 '25 11:09

Henry


1 Answers

It's now possible to denote the very end of string in multi-line mode with '\Z'.

Ref: https://docs.python.org/3.8/library/re.html

like image 172
George Avatar answered Sep 09 '25 01:09

George