首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python RE "re,findall“

Python RE "re,findall“
EN

Stack Overflow用户
提问于 2014-01-14 04:17:30
回答 3查看 611关注 0票数 2

提前谢谢你。我的问题是:

我有一段Python代码,我试图在其中使用"os.walk,re和re.findall ip“来查找几个文件中的所有ip地址,例如:

代码语言:javascript
复制
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

等等。我的代码块

代码语言:javascript
复制
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,例如:

代码语言:javascript
复制
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不接受我测试过的正则表达式?

EN

回答 3

Stack Overflow用户

发布于 2014-01-14 04:22:39

您只能打印出一个匹配项:

代码语言:javascript
复制
if matches:
    print "Here is what is inside %s = %s" % (file,matches[0])

而不是所有人

代码语言:javascript
复制
if matches:
    for match in matches:
        print "Here is what is inside %s = %s" % (file,match)
票数 6
EN

Stack Overflow用户

发布于 2014-01-14 04:23:06

您只打印第一个匹配项,并且-至少对于您所显示的数据集的一部分-第一个条目始终为192.168.3.1

也许你想打印所有的匹配?您可以使用以下命令完成此操作

代码语言:javascript
复制
print '\n'.join(matches) 
票数 1
EN

Stack Overflow用户

发布于 2014-01-14 04:25:38

你能只匹配第一行吗?尝试向您的正则表达式添加/m标志

代码语言:javascript
复制
pattern = re.compile("whatever",re.MULTILINE)

另请注意,如果要将模式与其中的组进行匹配,则findall将返回列表列表

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21100550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档