首页 > 解决方案 > 如何在python的多行字符串中使用具有不同模式的正则表达式

问题描述

如何在python的多行字符串中使用具有不同模式的正则表达式

str1 = ''''
  interface is up
  admin state is up
  mtu is 1500

 '''

 str2 = 'interface is up admin state is up'

 pat = re.compile(r"interface is ([A-za-z]+) admin state is ([A-za-z]+)")

 matches = pat.finditer(str2)

for match in matches:
    print match.group()
    print match.group(1)
    print match.group(2)

上面的正则表达式模式适用于 str2 (没有换行符)但不适用于具有相同文本但有换行符的 str1。

我也尝试过使用 re.M,但这似乎也不起作用。

我想用多行字符串上的不同模式过滤接口状态、管理状态和 mtu。

标签: python

解决方案


尝试更改您的模式以在之前选择包含换行符和空格admin state

r"interface is ([A-za-z]+)[\s\r\n]*admin state is ([A-za-z]+)"

例子

pat = re.compile(r"interface is ([A-za-z]+)[\s\r\n]*admin state is ([A-za-z]+)", re.MULTILINE)
matches = pat.finditer(str1)
for match in matches:
    print match.groups()
# ('up', 'up')

推荐阅读