Search code examples
pythonregexsubprocesspython-re

regex bug while printing an ip


import re

text = "|2018-11-03 18:20:59.0|FrozoneMD|8607446f-5748-479f-b72a-e0d25c1c7757|70.19.66.12|"
ip = re.findall("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}", text)
print(ip)

The program searches a txt file and finds this line using regex:

|2018-11-03 18:20:59.0|FrozoneMD|8607446f-5748-479f-b72a-e0d25c1c7757|70.19.66.12|

When I print the var ip, it prints this:

[('70', '.12', '12')]

Instead of:

[('70.19.66.12')]


Solution

  • You can use re.search() and just print group(0), if there are any matches

    import re
    
    text = "|2018-11-03 18:20:59.0|FrozoneMD|8607446f-5748-479f-b72a-e0d25c1c7757|70.19.66.12|"
    ip = re.search("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}", text)
    if ip:
        print(ip.group(0))
    else:
        print('none')
    

    Edit:

    If you need to get more than 1 matches, you can use re.finditer()

    import re
    
    text = "|2018-11-03 18:20:59.0|FrozoneMD|8607446f-5748-479f-b72a-e0d25c1c7757|70.19.66.12|\n|2018-11-03 18:20:59.0|FrozoneMD|8607446f-5748-479f-b72a-e0d25c1c7757|70.19.66.13|"
    ip = re.finditer("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}", text)
    for i in ip:
        print(i.group(0))
    

    Output:

    70.19.66.12
    70.19.66.13