-3

I have the following regex to match an IP address:

(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

Could someone please update it to allow for a port number on the end (port number would be optional)

Thanks in advance

Keir Nellyer
  • 913
  • 5
  • 12
  • 20

2 Answers2

1

Man, that's a mess. It's better to simplify the search pattern, and then validate values, rather than try to do everything in the regex. e.g.,

private String findIP(String in) {
  Matcher m = Pattern.compile("((\\d+\\.){3}\\d+):(\\d+)").matcher(in);
  if (m.find()) {
    String[] p = m.group(1).split("\\.");
    for (int i = 0; i < 4; i++)
      if (Integer.parseInt(p[i]) > 255) return null;
    if (Integer.parseInt(m.group(3)) > 65535) return null;
    return m.group(0);
  }
  return null;
}

I'm probably not taking everything into account (addresses starting with 0., parseInt returning negatives, etc.), but having a simpler regex pays off for readability, as well as having the numbers 4, 255, and 65535 be cues to the future reader that we're talking about a dotted quad and a port.

Curtis Autery
  • 76
  • 1
  • 4
  • +1, but a better regex is: "([012]?\\d{1,2})(\\.[012]?\\d{1,2}){3}(:(\\d{1,5}))?" – G. Blake Meike Mar 24 '13 at 16:43
  • Thanks Blake, I decided to use yours, I had to make a slight change to make the port optional (([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[\d]{1,5})?$ – Keir Nellyer Mar 27 '13 at 17:38
0
(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]{1,5}$
thoitbk
  • 269
  • 2
  • 9
  • 21