Python RegEx Matching Newline
I have the following regular expression:
[0-9]{8}.*n.*n.*n.*n.*
Which I have tested in Expresso against the file I am working and the match is sucessfull.
I want to match the following:
My python code is:
for m in re.findall('[0-9]{8}.*n.*n.*n.*n.*', l, re.DOTALL):
print m
But no matches are produced, as said in Expresso there are 400+ matches which is what I would expect.
What I am missing here?
Don't use re.DOTALL
or the dot will match newlines, too. Also use raw strings ( r"..."
) for regexes:
for m in re.findall(r'[0-9]{8}.*n.*n.*n.*n.*', l):
print m
However, your version still should have worked (although very inefficiently) if you have read the entire file as binary into memory as one large string.
So the question is, are you reading the file like this:
with open("filename","rb") as myfile:
mydata = myfile.read()
for m in re.findall(r'[0-9]{8}.*n.*n.*n.*n.*', mydata):
print m
Or are you working with single lines ( for line in myfile:
or myfile.readlines()
)? In that case, the regex can't work, of course.
上一篇: 使用Python解析HTML
下一篇: Python RegEx匹配换行符