Regular Expression
To use java regular expression you need to be familiar with java.util.regex.Pattern and java.util.regex.Matcher classes. Here is a short code on how to check if an IP address is valid.
// IPv4 Regular Expression Pattern
String IPV4PATTERN = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
// Compile the string pattern
Pattern pattern = Pattern.compile(IPV4PATTERN);
// IPs to check
String[] ips = new String[] { "192.168.1.1", "192.168.1.1000", "itcuties.com"};
// Check IPs
for (String ip: ips) {
// Create the matcher for a given IP
Matcher matcher = pattern.matcher(ip);
System.out.println(ip + " is " + (matcher.matches() ? "valid":"invalid"));
}
This code gives the following output:
192.168.1.1 is valid 192.168.1.1000 is invalid itcuties.com is invalid
At the beginning a regular expression pattern needs to be compiled by calling java.util.regex.Pattern.compile method which takes a regular expression string pattern as argument. Next we need a java.util.regex.Matcher object which is an engine that performs match operations on character sequences by interpreting the given pattern. By calling java.util.regex.Matcher.matches method a given string is validated with the pattern.
Here are some useful java regular expression patterns:
- IPv4 regular expression pattern
- URL regular expression pattern
- EMAIL regular expression pattern
IPv4 regular expression pattern
"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"
URL regular expression pattern
"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"
EMAIL regular expression pattern
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"

Leave a Reply
Want to join the discussion?Feel free to contribute!