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[] { "", "", ""};
	// 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: is valid is invalid 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


URL regular expression pattern


EMAIL regular expression pattern


4 Responses to "Regular Expression"

  1. Burke says:


    I’ll check back later and see if the problem still exists.

  2. Parag says:

    I actually wanted to know the meaning of patterns like


    in detail.


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply


