zoukankan      html  css  js  c++  java
  • Java Regex match IP address

    Reference:

    [1] https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class IPAddressValidator{
    
        private Pattern pattern;
        private Matcher matcher;
    
        private static final 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])$";
    
        public IPAddressValidator(){
    	  pattern = Pattern.compile(IPADDRESS_PATTERN);
        }
    
       /**
        * Validate ip address with regular expression
        * @param ip ip address for validation
        * @return true valid ip address, false invalid ip address
        */
        public boolean validate(final String ip){
    	  matcher = pattern.matcher(ip);
    	  return matcher.matches();
        }
    }
    

    Description

    ^		#start of the line
     (		#  start of group #1
       [01]?\d\d? #    Can be one or two digits. If three digits appear, it must start either 0 or 1
    		#    e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
        |		#    ...or
       2[0-4]\d	#    start with 2, follow by 0-4 and end with any digit (2[0-4][0-9])
        |           #    ...or
       25[0-5]      #    start with 2, follow by 5 and ends with 0-5 (25[0-5])
     )		#  end of group #2
      .            #  follow by a dot "."
    ....            # repeat with 3 times (3x)
    $		#end of the line
    

    Whole combination means, digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255”

  • 相关阅读:
    新年献礼 技术胖262集前端免费视频 让您走的更容易些
    Eruda 一个被人遗忘的调试神器
    你(可能)不知道的web api
    含有阶乘的幂级数和
    sin x 特解的假设
    将y=arctanx展开为x的幂级数
    判断数项级数是否收敛
    ubuntu中用安装字体的方法解决文档中的音标乱码
    英语单词
    用递归实现汉诺塔
  • 原文地址:https://www.cnblogs.com/codingforum/p/5811907.html
Copyright © 2011-2022 走看看