简体   繁体   中英

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) . For example:

Valid IP

  • 0.0.0.*
  • 255.255.255.*

Invalid IP

  • 0.*
  • 255.*
  • 256.*
  • 0.0.*
  • 255.255.*
  • 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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