20

In an application, I get strings containing IP Addresses but these string have no precise format. All we know is that these strings may contain an IP address.

here's an example of what the string can look like :

  • "XPSPort"
  • "IP_10.29.167.187"
  • "10.29.166.193"

I would like to get a Java code that extracts the ip address of the string if there is one or that returns "" if the string doesn't contain an ip address.

I tried this code but it doesn't work :

String IPADDRESS_PATTERN = 
        "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(ipString);
        if (matcher.find()) {
            return matcher.group();
        }
        else{
            return "0.0.0.0";
        }

I'm pretty sure using RegExp is the best way to achieve that but I'm not very good with these so can someone help me find the good RegExp?

Thanks in advance.

Padrus
  • 2,013
  • 1
  • 24
  • 37
  • possible duplicate of [regex ip address from string](http://stackoverflow.com/questions/8439633/regex-ip-address-from-string) – Richard Apr 08 '13 at 09:01
  • 1
    Thanks Richard, this is not exactly a duplicate because in my case the IP is not always a full word but it helped me find the answer. – Padrus Apr 08 '13 at 09:17
  • 1
    It's nice to remember the existence of the non-capturing group operator. But, your solution give more matches than there should be (19 vs 13). I have the expected matches with this regex `^(?:([01]?[0-9]?[0-9]|25[0-5]|2[0-4][0-9])\.){3}([01]?[0-9]?[0-9]|25[0-5]|2[0-4][0-9])$` (try it here https://regex101.com/r/8I7amT/7). If you want to have fun here there is the [HackerRank exercise](http://hr.gs/dwx) – tuxErrante Jun 19 '18 at 14:29
  • @bastaPasta strangely none of the patterns mentions here, even the one as the author accepted as answer, worked for me except your pattern! Not sure why. Thanks – xbmono Jan 16 '19 at 23:18
  • Happy to have helped! – tuxErrante Jan 17 '19 at 14:15

4 Answers4

45

Richard's link helped me find the answer. here's the working code :

String IPADDRESS_PATTERN = 
        "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(ipString);
if (matcher.find()) {
    return matcher.group();
} else{
    return "0.0.0.0";
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Padrus
  • 2,013
  • 1
  • 24
  • 37
  • When give a string http://256.225.255.255:8690/AppPortal/ returning ip address as 56.225.255.255. – Arundev Jun 16 '14 at 11:16
  • 7
    that's because 256.255.255.255 is not a valid ip address, the maximum number is 255. – Padrus Jun 17 '14 at 14:53
  • 1
    The reason this works is because the ^ and $ are not there. Your original regexp would have worked too without those chars. Those characters denote the beginning and end of the string, thus a regex containing those two will not match an address that is found within the string. – Sean F Oct 19 '16 at 01:58
  • "0.0.0.256" will be also be recognized as valid IP address, which it's not. Adding word boundries around the patter solves the problem as follows `String IPADDRESS_PATTERN = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";` – Shrikant Prabhu Mar 21 '18 at 08:03
15

IPV4_PATTERN = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"

evandrix
  • 6,041
  • 4
  • 27
  • 38
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
10

Check this solution to validate both IPV4 & IPV6 addresses.

/**
 * This class provides a variety of basic utility methods that are not
 * dependent on any other classes within the org.jamwiki package structure.
 */
public class Utilities {
  private static Pattern VALID_IPV4_PATTERN = null;
  private static Pattern VALID_IPV6_PATTERN = null;
  private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
  private static final String ipv6Pattern = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";

  static {
    try {
      VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
      VALID_IPV6_PATTERN = Pattern.compile(ipv6Pattern, Pattern.CASE_INSENSITIVE);
    } catch (PatternSyntaxException e) {
      //logger.severe("Unable to compile pattern", e);
    }
  }

  /**
   * Determine if the given string is a valid IPv4 or IPv6 address.  This method
   * uses pattern matching to see if the given string could be a valid IP address.
   *
   * @param ipAddress A string that is to be examined to verify whether or not
   *  it could be a valid IP address.
   * @return <code>true</code> if the string is a value that is a valid IP address,
   *  <code>false</code> otherwise.
   */
  public static boolean isIpAddress(String ipAddress) {

    Matcher m1 = Utilities.VALID_IPV4_PATTERN.matcher(ipAddress);
    if (m1.matches()) {
      return true;
    }
    Matcher m2 = Utilities.VALID_IPV6_PATTERN.matcher(ipAddress);
    return m2.matches();
  }
}

source: Determine if the given string is a valid IPv4 or IPv6 address.

Pascal
  • 15,257
  • 2
  • 52
  • 65
0

IP Address Regular Expression Pattern:

^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$

For reference with examples click here

Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40