提前致谢。我的问题是:
我有一段 Python 代码,我在其中尝试使用“os.walk,re and 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 不接受我测试过的正则表达式?
最佳答案
你只打印了一场比赛:
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)
关于 python RE "re,findall",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21100550/