正则表达式匹配 - 为什么这不匹配并返回 None? [英] Regex matching - why does this not match and return None?
问题描述
我不明白为什么这个简单的正则表达式匹配不返回匹配对象.它返回 None 我做错了什么?
我是个新手(昨天开始),想编写一个小程序,在文件夹树中搜索某些文件,打开这些文件并在这些文件中找到某些行,然后将这些行打印到一个新文件中.为了完成第一步,我想匹配 os.walk 返回的文件名并将它们与某个模式匹配.所以现在我正在检查正则表达式是如何工作的,据我所知,下面的代码应该匹配,但是当我打印一个时,我得到了 None.我不明白为什么,它不应该返回任何以 9 开头的文件吗?
import os, fnmatch, re模式=重新编译(r'^9')teststring="9-ZnPc.dat"a=pattern.match(teststring, re.I)打印一个输出:无
因为你应该将 re.I
传递给 compile()
,而不是 match()
.
I don't understand why this simple regex match does not return a match object. It returns None what am I doing wrong?
I'm a total newby(started yesterday) and want to write a small program that searches folder trees for certain files, open these files and find certain lines in these files, and print the lines into a new file. To complete the first step I want to match the filenames returned by os.walk and match them with a a certain pattern. So right now I'm checking out how regexes work and to my understanding the code below should give a match, but when I print a I get None. I don't understand why, shouldn't it return any file starting with a 9?
import os, fnmatch, re
pattern = re.compile(r'^9')
teststring= "9-ZnPc.dat"
a=pattern.match(teststring, re.I)
print a
Output: None
Because you should be passing the re.I
to compile()
, not match()
.
>>> pattern = re.compile(r'^9', re.I)
>>> a=pattern.match(teststring)
>>> print a
<_sre.SRE_Match object at 0x1140168>
这篇关于正则表达式匹配 - 为什么这不匹配并返回 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!