Skip to content Skip to sidebar Skip to footer

How To Modify Regular Expression For Ip:port?

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 regu

Solution 1:

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)

Solution 2:

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})))?$|^$

Post a Comment for "How To Modify Regular Expression For Ip:port?"