提前谢谢你。我的问题是:
我有一段Python代码,我试图在其中使用"os.walk,re和re.findall ip“来查找几个文件中的所有ip地址,例如:
file1:192.168.3.1
file1:192.168.3.2
file1:mary had a little lamb
file1:192.168.3.3
file1:192.168.3.11
file1:10.255.3.1
file10:192.168.3.1
file10:192.168.3.2
file10:192.168.3.3
file10:192.168.3.4
file10:192.168.3.11
file10:192.168.1.1
file10:10.255.3.1
file2:192.168.3.1
file2:192.168.3.2
file2:192.168.3.3
file2:192.168.3.4
file2:192.168.3.11
file2:192.168.1.1
file2:10.255.3.1
file3:192.168.3.1
file3:192.168.3.2
file3:192.168.3.3
file3:192.168.3.4
file3:192.168.3.11
file3:192.168.1.1
file3:10.255.3.1等等。我的代码块
for subdir, dirs, files in os.walk('.'):
for file in files:
matches = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", open(file, "r").read())
if matches:
print "Here is what is inside %s = %s" % (file,matches[0])结果是它只列出了一种特定类型的ip,例如:
Here is what is inside file3 = 192.168.3.1
Here is what is inside file6 = 192.168.3.1
Here is what is inside file7 = 192.168.3.1
Here is what is inside file1 = 192.168.3.1
Here is what is inside file9 = 192.168.3.1
Here is what is inside file5 = 192.168.3.1
Here is what is inside file8 = 192.168.3.1
Here is what is inside file10 = 192.168.3.1
Here is what is inside file4 = 192.168.3.1我认为这是我的正则表达式不正确,所以我用http://gskinner.com/RegExr/进行了测试
正则表达式对我在站点提供的数据进行了良好的测试,因为它可以找到ip地址的所有内容。我做错了什么?为什么re.findall不接受我测试过的正则表达式?
发布于 2014-01-14 04:22:39
您只能打印出一个匹配项:
if matches:
print "Here is what is inside %s = %s" % (file,matches[0])而不是所有人
if matches:
for match in matches:
print "Here is what is inside %s = %s" % (file,match)发布于 2014-01-14 04:23:06
您只打印第一个匹配项,并且-至少对于您所显示的数据集的一部分-第一个条目始终为192.168.3.1。
也许你想打印所有的匹配?您可以使用以下命令完成此操作
print '\n'.join(matches) 发布于 2014-01-14 04:25:38
你能只匹配第一行吗?尝试向您的正则表达式添加/m标志
pattern = re.compile("whatever",re.MULTILINE)另请注意,如果要将模式与其中的组进行匹配,则findall将返回列表列表
https://stackoverflow.com/questions/21100550
复制相似问题