python RE "re,findall"

标签 python regex

提前致谢。我的问题是:

我有一段 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/

相关文章:

正则表达式问题通过 curl 向 Varnish 服务器发送 BAN 请求

php - 如何从字符串中删除所有数字?

Python:字符串无法识别达到一定数量的两位数

python - 寻找更好的方法来计算矩阵

python - “NoneType”对象在 24 小时自学 Python 的第 9 章中没有属性 '__getitem__'

Python 3 网络摄像头

python - 如何解决在 python 中使用 unicode 打印扑克牌的问题?

regex - Visual Studio在字符类中查找并替换右方括号]

MySQL - 在子查询的别名上使用 REGEXP

regex - 使用 sed 将文件中的字符串替换为该名称变量的内容