Python regex capture whole integer

Question:

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

Asked By: xancho

||

Answers:

.* 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")
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.