python - Where do I add in an re.search in this python code?
问题描述
I have some python code to change the severities of incoming SNMP traps on the NMS I am using.
The incoming SNMP traps contain objects that are ranges of numbers for a given severity level. The below code works if the the incoming object numbers are singular, 1,2,3,4,5 etc. But it doesnt work for the below when trying to match a regex number range.
## This gets the alarmTrapSeverity function and creates a variable called Severity to hold the value
if getattr(evt, 'alarmTrapSeverity', None) is not None:
Severity = getattr(evt, 'alarmTrapSeverity')
## This part runs through the Severity to assign the correct value
if str(Severity) == '0':
evt.severity = 0
elif str(Severity) == '([1-9]|1[0-9])':
evt.severity = 1
Please could you advise the correct way to do this. My regex skills are still developing.
解决方案
如果我理解正确,在 else-if 语句中,您希望执行正则表达式搜索以确认匹配。我的方法看起来像这样,
## This gets the alarmTrapSeverity function and creates a variable called
Severity to hold the value
if getattr(evt, 'alarmTrapSeverity', None) is not None:
Severity = getattr(evt, 'alarmTrapSeverity')
regex = re.compile(r'([1-9]|1[0-9])')
## This part runs through the Severity to assign the correct value
if str(Severity) == '0':
evt.severity = 0
elif regex.search(str(Severity)) != None:
evt.severity = 1
这将在 str(Severity) 变量中搜索匹配的子字符串,在本例中是包含 1-19 之间数字的字符串。然后只要找到匹配项,设置 evt.severity = 1。
此外,回顾您的问题,如果您在使用该正则表达式查找 1-19 之间的数字时遇到问题,另一个可行的示例可能是,
"10|1?[1-9]"
推荐阅读
- javascript - 如何正确处理 MongoDB bulkwrite 中的错误?
- c# - 使很长的 switch 语句更具可读性
- javascript - 在每个浏览器中以相同的方式操作
- azure-active-directory - OWIN 身份验证 cookie 是否容易受到攻击?
- python-3.x - 递归冰雹序列(Python 3.x)返回一个平面列表
- ios - UIImageView 中的 Swift 4 UIButton 操作不起作用
- python - How to finish the code using recursion?
- php - 在 Silverstripe 4 中,GridField 的标准“添加”按钮什么也不做
- javascript - 同时使用 Onkeyup 和 Onchange
- c - 将用户输入写入文件,然后读取它