简体   繁体   中英

How to parse IP Address or Host name containing Alpha Characters?

I am trying to separate two different types of Strings, IP addresses and DNS addresses. I am having trouble figuring out how to split it. My initial thought is:

String stringIP = "123.345.12.1234";
String stringDNS = "iam.adns234.address.com";

if(!Pattern.matches("^[a-zA-Z0-9.]*$",stringDNS)){
    //I only want to get IP type strings here, so I am trying to separate out anything containing alpha characters. `stringDNS` should not be allowed into the if statement.
}

You can "validate" your IP with the following pattern:

String stringIP = "123.345.12.1234";
String stringDNS = "iam.adns234.address.com";
//                | start of input
//                | | 1-4 digits
//                | |      | dot
//                | |      |    | 3 occurrences
//                | |      |    | | 1-4 digits
//                | |      |    | |       | end of input
String pattern = "^(\\d{1,4}\\.){3}\\d{1,4}$";
System.out.println(stringIP.matches(pattern));
System.out.println(stringDNS.matches(pattern));

Output

true
false

Note

Validation here is "lenient", insofar as it won't check the values and will fit your example with up to 4 digit items.

For a more serious validation (with the down side of a less readable pattern), see dasblinkenlight 's answer.

public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
if(string.matches(IPV4_REGEX)
{
    //....
}

Note that the IP address you posted "123.345.12.1234" is not a valid IPV4 addrss.

Your implementation would let through some strings that do not represent a digital IP address. It is better to use a regex that passes through only valid numeric IP addresses. The regex is taken from here . It is somewhat complex, because it needs to ensure that multi-digit numbers are below 256, but it is a solid way of validating a numeric IP address:

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])$";
if(Pattern.matches(IPADDRESS_PATTERN, stringIP)) {
    ...
}

As validating a domain String is a more complex task, if you don't mind, you can add an extra lightweight apache commons library to your project.

Have a look at DomainValidator.isValid(String) .

Please note that this method also checks for valid well-recognized top-level domain names (.com, .org, etc).

For validating IP addresses have a look at InetAddressValidator.isValidInet4Address(String) .

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