Search code examples
regexpython-2.7ip-address

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 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.


Solution

  • 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)