Search code examples
python-3.xregexfindall

Python Regex: How to print the entire word that matches a string using the number keyword?


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']

Solution

  • 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'
    ]