Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading