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 regex capture whole integer

I am trying to extract several parts of a string from a log file. I can match the number I want, but only the first digit. There is a related question here, but it tries the opposite: matching only the beginning of an integer.

Here is a minimal working example:


import re
regex = re.search(
                r'.*(?P<line_number>\d+).*(?P<line2_number>\d+)',
                "adding 2000 to database, removing 3000")
if regex:
    print("Regex matched!")
    print("Line number : {}".format(regex.group("line_number")))
else:
    print("Regex didn't match!")

Output:
Line number : 0
Expected:
Line number : 2000

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 :

.* at start and in the middle of your regex consumes anything including digits (the last one is still matched so the regex engine respects the "one digit or more" condition).

You have to exclude digits. Using \D does exactly that.

regex = re.search(
                r'\D*(?P<line_number>\d+)\D*(?P<line2_number>\d+)',
                "adding 2000 to database, removing 3000")
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