python-3.x - Python正则表达式在多行中编译匹配
问题描述
多行正则表达式搜索以构建列表
我曾尝试使用带有特定模式的 re.compile 以及标志 re.MULTILINE 但它不起作用。
rx_dict = {
'user_db_pppoe' : re.compile(r"sap-session-limit\s\d{5}\n\s+(?P<USERDB_P>.*)\w+")
}
with open('test_input.txt', 'r') as file_object:
if key == 'user_db_pppoe':
print(match)
配置:
pppoe
policy "pppoe-change-mtu"
session-limit 32767
sap-session-limit 32767
user-db "LAC-l2tp-DXB"
no shutdown
exit
exit
但是多行不接受 re 模块
rx_dict = {
'user_db_pppoe' : re.compile(r"sap-session-limit\s\d{5}\n\s+(?P<USERDB_P>.*)\w+" , re.MULTILINE)}
我要求在此处匹配 user-db 值“LAC-l2tp-DXB”,它遵循 sap-session-limit 值。
解决方案
您的代码存在一些问题,这里有一种注释方式(假设您的问题中的“配置”是test_input.txt
内容:
### specify both substring you want to find in the line
rx_dict = {
'user_db' : re.compile(r"LAC-l2tp-DXB"),
'sap_session_limit' : re.compile(r"sap-session-limit")
}
### open the file
with open('test_input.txt', 'r') as file_object:
### start a counter to remember line number
line_count = 0
### open loop over the file line (you have to use string for regex, nt as you did in example on file_object)
for line in file_object :
### if found first ocurrence remember line number of first match
if (rx_dict['sap_session_limit'].search(line)) :
sap_line = line_count
### if found second one AND the line is the next to first ocurrence find
if (rx_dict['user_db'].search(line) and line_count == (sap_line + 1)) :
### ... do what you want to do ...
print(line)
### increase counter
line_count += 1
这可以满足您的要求。另请注意,您使用了错误的字典键参考,请查看文档以正确使用键和值。
推荐阅读
- python - 如何在 Pandas Dataframe 中获取特定组的重叠记录
- sql - 如何在 Excel 中显示来自 Access 的二维数组记录集?
- javascript - 单击图标清除输入时失去焦点
- selenium-webdriver - 在 Robot Framework 中运行 Edge 无头模式
- html - 如何在 Outlook 邮件的图像之间留出空格
- python - 提取python pandas Dataframe中单个列中包含的分组
- c++ - 为什么静态数据成员可以有不完整的类型?
- python - 无法在熊猫中旋转数据框
- ios - iOS - App Store Connect 下载了带有隐藏符号的 dSYM
- javascript - 我怎么不能在浏览器检查器中调查 HTML 的一部分?