简体   繁体   English

RegEx在Java中使用通配符验证IP地址(仅最后一个索引)

[英]RegEx to validate ip address with wildcard (last index only) in Java

I can't seem to get the proper RegEx for validating an IP address, including support for a wildcard char (*), which can occur only at the end (last index) means * (asterisk) can only available after 3rd '.'(dot) . 我似乎无法获得用于验证IP地址的正确RegEx,包括对通配符char(*)的支持,通配符char(*)只能出现在末尾(最后一个索引),意味着*(星号)只能在第3个“。”之后使用。 (点)。 For example: 例如:

Valid IP 有效IP

  • 0.0.0.* 0.0.0。*
  • 255.255.255.* 255.255.255。*

Invalid IP 无效的IP

  • 0.* 0. *
  • 255.* 255. *
  • 256.* 256. *
  • 0.0.* 0.0。*
  • 255.255.* 255.255。*
  • 256.256.* 256.256。*
String regex = "^((0|255)\\.){3}([0-9]|[1-9][0-9]|[1-2][0-5][0-5])$";

You can use below code for identifying IP address 您可以使用以下代码来标识IP地址

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();
    }
}

Could change Regex according to your requirement 可以根据您的要求更改正则表达式

Something like this should do it: 这样的事情应该做到:

^(?:(?: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]?|\*)$

Quite accurate i think for this purpose 我认为非常准确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM