Extract ip addresses from Strings using regex

后端 未结 4 1390
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 07:53

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\'

相关标签:
4条回答
  • 2020-11-29 08:05

    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}$"

    0 讨论(0)
  • 2020-11-29 08: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.

    0 讨论(0)
  • 2020-11-29 08:10

    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

    0 讨论(0)
  • 2020-11-29 08:22

    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";
    }
    
    0 讨论(0)
提交回复
热议问题