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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With