Вопрос

I have regular expression like

match = re.findall(r'[0-9]+(?:\.[0-9]+){3}', source)

It works fine to take something like 192.168.1.1 from source string. How I can modify this regular expression for make it work with something like this:

192.168.1.1:80

Thank You for help.

P.S. Sorry for my bad english.

Это было полезно?

Решение

This will match IP addresses with ports numbers.

match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', source)

If you want to make it flexible to match IP address without the ports and With the ports, you can use:

match = re.findall(r'[0-9]+(?:\.[0-9]+){3}(:[0-9]+)?', source)

Другие советы

Since the highest port number ((2^16 - 1) or 65,535) is not taken into account (in the solution above), this should be the regular expression for your case:

^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}(:((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{1,5})|([0-9]{1,4})))?$|^$
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top