pythonregexip-addresspython-renamed-captures

Only match IP addresses and not other numbers


I​ want the following regex code to return an output of IP addresses without returning other number values as IP from the source file.

The Code:

import re

logdata = 146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622
for item in re.finditer("(?P<host>[\d.]+)", logdata):
    print(item.groupdict())

Required output:

{'host': '146.204.224.152'}

U​nwanted output:

{'host': '6811'}

Solution

  • I think this should do it:

    (?P<host>(\d+\.){3}\d+)