python - 如何在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。
解决方案
尝试更改您的模式以在之前选择包含换行符和空格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')
推荐阅读
- sql-server - 如何使用 T-SQL 在一个查询结果中获得多选
- python - 仅在数据框中提取最小值
- c# - 如何使用相同的过滤器同时过滤集合及其嵌套集合?
- c# - Application Insight 中的范围日志记录
- python - C++ DLL 中的 Python 对象
- google-api - Google 登录同意页面未针对我的应用程序请求的所有范围请求许可
- c++ - Windows 控制台调整大小被忽略 - 屏幕缓冲区搞砸了
- python - for循环中某些值的条件(Python pandas)
- java - 发布密钥无法与已部署的应用程序一起使用
- javascript - 访问 localstorage 中的 `access_token` 属性