Radek Z Radek Z - 6 months ago 8
Python Question

Python: How to find IP adress in text?

tekst= "asdadsasdas 192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa"
import re
szukane = r'\d{1,3}.+'
znalezione = re.search(szukane, tekst)

if znalezione:
co= znalezione.group()
print(co)


I'm looking for IP adress, after run this i got:

192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa


What should i change and why?

Answer

. is not a literal period in regex. It represents all characters. You'll need to escape it with a backslash. Also, don't forget to include the last group of digits that is not followed by a period.

szukane = r'(?:\d{1,3}\.)+(?:\d{1,3})'

Result:

>>> re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', "asdadsasdas 192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa")
['192.168.1.1', '10.22.10.5', '172.10.5.1']
Comments