Python关于芬德尔有多种图案

2024-09-22 16:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其条目如下:

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

我想解析它,只得到对应于Interface01的IP地址

我用pythonre.finall尝试过may-things,但是没有得到任何匹配的东西

^{pr2}$

但什么都不管用。在

预期结果是192.168.0.1。在


Tags: 条目mayinterfacenext文本文件thingspr2pythonre
3条回答
interface = re.findall(r'Interface01 :\s*.adress\s*(.*?)$',txt,re.S|re.M)        

你可以用

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

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

图案细节

  • Interface01-一个文本子字符串
  • \s*:\s*-a:用0+空格括起来
  • adress-一个文本子字符串
  • \s+-1+个空格
  • (.*)-组1:除换行符之外的任何0+字符。在

Python demo

^{pr2}$

创建一个写着“Interface01”的模式,然后跳过所有不是数字的字符,然后得到数字和点?在

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

结果:

^{pr2}$

更新

感谢@zipa,以下是更新的regex:

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

结果:

['192.168.0.1', '172.123.456.123'

相关问题 更多 >