繁体   English   中英

带有多种模式的Python re.findall

[英]Python re.findall with multiple patterns

我有一个文本文件,其中包含以下内容:

 Interface01 :
     adress
        192.168.0.1
next-interface:
 interface02:
     adress
        10.123.123.214
next-interface:
 interface01 :
     adress
        172.123.456.123

我想解析它并仅获取与Interface01对应的IP地址

我用python re.finall尝试了一些东西,但没有任何匹配的东西

 i = open(f, r, encoding='UTF-8')
 txt = i.read()
 interface = re.findall(r'Interface01 :\s*(.adress*)n',txt,re.DOTALL)

但没有任何效果。

预期的结果是192.168.0.1

如何创建表示“ Interface01”的模式,然后跳过所有非数字字符,然后获取数字和点?

re.findall(r'Interface01[^0-9]+([0-9.]+)', text)

结果:

['192.168.0.1']

更新

感谢@zipa,这是更新的正则表达式:

re.findall(r'[iI]nterface01[^0-9]+([0-9.]+)', text)

结果:

['192.168.0.1', '172.123.456.123'

您可以使用

Interface01\s*:\s*adress\s+(.*)

参见regex演示 在Python中,因为您只想提取1个IP地址,所以使用re.search获取第一个匹配项。

图案细节

  • Interface01文字子字符串
  • \\s*:\\s* -a :包含0+空格
  • adress -文字子字符串
  • \\s+ -1+空格
  • (.*) -组1:除换行符以外的任何0+字符。

Python演示

import re
reg = r"Interface01\s*:\s*adress\s+(.*)"

with open('filename') as f:
    m = re.search(reg, f.read())
    if m:
        print(m.group(1))

# => 192.168.0.1
interface = re.findall(r'Interface01 :\s*.adress\s*(.*?)$',txt,re.S|re.M)        

您可以尝试这样的事情:

interface = re.findall(r'Interface01 :\n +adress\n +(\d+.\d+.\d+.\d+)', txt)
# ['192.168.0.1']

为了获得一场比赛,最好使用re.serach()函数:

import re

with open('filename') as f:
    pat = r'Interface01 :\s*\S+\s*((?:[0-9]{1,3}\.){3}[0-9]{1,3})'
    result = re.search(pat, f.read()).group(1)

print(result)

输出:

192.168.0.1

您可以使用Interface01 :\\n.*?\\n(.*)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM