Extract ip addresses from Strings using regex

后端 未结 4 1406
伪装坚强ぢ
伪装坚强ぢ 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: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";
    }
    

提交回复
热议问题