I want to print the whole words that match the given string using the number keyword but it only prints numbers. Could anyone help with this?
import re
string = ''' '%SYSDB-SYSDB-6-TIMEOUT_EDM',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY',
'%SYSDB-SYSDB-6-TIMEOUT_EDM',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY'
'''
output = re.findall(r"-[1-4]-", string)
print(output)
Current Output ['-3-', '-4-', '-3-', '-4-']
Expected Output:
['%HA-HA_WD-3-DISK_ALARM_ALERT',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY']
CodePudding user response:
You can enclose your string with [
and ]
, then use ast
to cast the result to a string list, and then filter that list with your regex:
import re, ast
s = ''' '%SYSDB-SYSDB-6-TIMEOUT_EDM',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY',
'%SYSDB-SYSDB-6-TIMEOUT_EDM',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY'
'''
l = ast.literal_eval(f'[{s}]')
rx = re.compile(r"-[1-4]-")
print(list(filter(rx.search, l)))
See the Python demo.
Output:
[
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY',
'%HA-HA_WD-3-DISK_ALARM_ALERT',
'%ROUTING-FIB-4-RETRYDB_NONEMPTY'
]
CodePudding user response:
Use capturing groups in your regex:
output = re.findall(r"'(. -[1-4]-. )'", string)