Search code examples
pythonfor-looppython-re

Python: .group "AttributeError: 'NoneType' object has no attribute 'group'"


When i put the .group() inside the "FOR" loops I get an error.

import re

with open(r'C:\Users\testuser\OneDrive - personal\Network\network.log', 'r+') as LOG:
    OUTPUT = LOG.readlines()

    for LINE in OUTPUT:
        x = re.search(r'\s+name ".*"', LINE).group()
        print(x)
 x = re.search(r'\s+name ".*"', LINE).group()
AttributeError: 'NoneType' object has no attribute 'group'

Process finished with exit code 1

However if i simply delete ".group()" the script executes as expected. However I don't wish for the value None or **<re.Match object; span=(0, 30), match=' name "Default Access Rule"'> ** I just want the the value that matches the pattern to be returned.


Solution

  • You need to check if there are no matches in some lines.

    import re
    
    with open(r'C:\Users\testuser\OneDrive - personal\Network\network.log', 'r+') as LOG:
        OUTPUT = LOG.readlines()
    
        for LINE in OUTPUT:
            x = re.search(r'\s+name ".*"', LINE)
            if x is not None:
                print(f'Got match: {x.group()}')
    
            # Otherwise there is not match in the line.