【发布时间】:2016-09-22 02:08:46
【问题描述】:
我有一个日志文件,至少有一千行
abc.txt:
1. example eg, ham, cheese 350.122.345.8
2. cheese ham eg, example 231.242.1.2
3. Ham cheese, example,e.g 100.200.100.200
4.
5. Ham cheese, example,e.g 100.200.100.200
1000.
我想要的最终结果:
仅打印与 IP 地址范围内的数字匹配的行。因此它应该只打印:
2. cheese ham eg, example 231.242.1.2
3. Ham cheese, example,e.g 100.200.100.200
5. Ham cheese, example,e.g 100.200.100.200
我尝试了以下代码,但无法得到我想要的结果:
import re
txt=open('/sdcard/Download/abc.txt','r')
pattern=re.compile('(^[2][0-5][0-5]|^[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})$', re.DOTALL)
for line in txt:
if str(pattern) in line:
print line
else:
print 'WRONG LINE:',line
返回的结果是打印出的完整行列表并显示我的 else WRONG LINE 消息。
我用在线检查器检查了我的正则表达式,它显示了正确的行为,匹配所有不超过 .255 的 ipv4 地址
请指出错误。
【问题讨论】:
-
str(pattern) in line不是你想要的。你需要re.search或re.match之类的东西。 -
if re.search(pattern, line) print bla -
如果你使用编译模式,你必须使用它的搜索或匹配方法。 docs.python.org/2/library/re.html#re.compile
-
另外,你也可以
print(str(pattern))看看这不是你想要的 -
@rock321987 应该类似于
if pattern.search(line): print line
标签: python regex ip-address ipv4