Skip to content Skip to sidebar Skip to footer

Python Regular Expression Not Matching File Contents With Re.match And Re.MULTILINE Flag

I'm reading in a file and storing its contents as a multiline string. Then I loop through some values I get from a django query to run regexes based on the query results values.

Solution 1:

According to documentation, re.match never allows searching at the beginning of a line:

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

You need to use a re.search:

regexString = r"^\s*"+item.feature_key+":"
pq = re.compile(regexString, re.M)
if pq.search(data):

A small note on the raw string (r"^\s+"): in this case, it is equivalent to "\s+" because there is no \s escape sequence (like \r or \n), thus, Python treats it as a raw string literal. Still, it is safer to always declare regex patterns with raw string literals in Python (and with corresponding notations in other languages, too).


Post a Comment for "Python Regular Expression Not Matching File Contents With Re.match And Re.MULTILINE Flag"