如何在 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,但这似乎也不起作用。
我想在多行字符串上用不同的模式过滤接口(interface)状态、管理状态和 mtu。
请您参考如下方法:
尝试更改您的模式以选择性地在 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')
