我试图从二进制文件中提取一些字符串.当我在linux中使用这个带有字符串的正则表达式时它工作正常,但它在python中不起作用.
在字符串中:
strings -n 3 mke2fs | grep -E '^([0-9][0-9]*(\.[0-9]+)+)'
Run Code Online (Sandbox Code Playgroud)
结果:1.41.11
在python中:
import re
f = open("mke2fs","rb").read()
for c in re.finditer('^([0-9][0-9]*(\.[0-9]+)+)',f):
print c.group(1)
Run Code Online (Sandbox Code Playgroud)
结果是空的.我该如何解决这个问题?是因为我的Python版本(我使用的是Python 2.7)?我尝试使用正则表达式(另一种替代方案)仍然没有结果.
您需要re.MULTILINE标记^来处理您的文本,如grep do.
顺便说一下,使用起来更具可读性\d:
for c in re.finditer(r'^(\d+(\.\d+)+)', f, re.MULTILINE):
print c.group(1)
Run Code Online (Sandbox Code Playgroud)