首页 > 解决方案 > 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.

标签: pythonregex

解决方案


如果我理解正确,在 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]"

推荐阅读