Regular Expression part 2 in java

In the part 1 , we have seen what is regular expression and its syntax. In part 2, we will understand how to use regular expression with examples.

Example 1:

We can use any string as regular expression. Let’s consider a string “I like this book” is an output of a any program. Depending on some conditions , the string may vary like “I like this movie”, “I like this house” etc.. As you can observe, only words are changing like movie, house, book etc.

Now, our requirement is we need to create a regular expression which can fit for all string output. Let’s see what we can do?

"I like this \\w+"

As you can observe, we have used character class (\w) and quantifier (+) for making this regular expression. ‘\w’ means match word character and ‘+’ means match one or more characters.Now, the pattern will match any word instead of ‘book’.

Now, suppose you got the string “I like this – book”. In that case, regular expression will fail because it one character ‘-‘ which is not handled in regular expression pattern. To match this string , we have tweak our pattern a bit which will be like given below.

"I like this -? \\w+"

Now, it will match with the strings like “I like this – book”,I like this – movie” etc.

Example 2:

Now, suppose we know the output string in advance, so we will be aware of all the words like movie, book, house etc. In that case, we can group all these words together and put an OR condition. Let’s see how to do this.

We can use ‘()‘ to group and a meta-character ‘|’ (pipe symbol) to specify all words which can match with the regular expression.

"I like this -? (book|movie|house|laptop)"

This way we can do the grouping for multiple expressions.  Let’s few matched or unmatched string with the above expression.

"I like this - book"     matches
"I like this book"        matches quantifier ? says match once or not at all
"I like this - movies"   didnt match .. extra s in the movie word
"I like this : book"     didnt match symbol (:) not recognised
"I like this - house:   matches

Example 3:

In this example, we will have pattern defined for IP address and then we will validate it against multiple IP address. Regular expression returns true if matches else false. We can use this kind of validation for other input like email id, phone number or some web form data etc.

Let’s understand with an example.

public class ValidateIpEx {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("122.234.124.222");
		list.add("111.123.23.23");
		list.add("187-56-123.121");
		list.add("111.222.23");
		list.add("1.1.1.1");
		list.add("1234.111.1.1");


		for (String ip : list) {
			if (ip.matches("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$")) {
				System.out.println("Valid ip : " + ip);
			}
		}
	}
	       
}
Output:
Valid ip : 122.234.124.222
Valid ip : 111.123.23.23
Valid ip : 1.1.1.1

Example 4:

In this example, we have created a regular expression for a customized email id as er our requirement. Rules are not for actual email formatting but just to understand the usage of regular expression.

Rules are like part before ‘@’ can accept alphabets, numeric, underscore(_), plus sign(+) ,hyphen(-) and after ‘@’ it should have a pattern like gmail.com, yahoo.com, abc.net etc.

Let’s check out the example.

public class ValidateEmailEx {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("[email protected]");          // valid 
		list.add("[email protected]");  //valid (underscore is allowed)
		list.add("[email protected]");  // invalid (? is not allowed)
		list.add("[email protected]");       //valid    (alphabet and numeric are allowed)
		list.add("[email protected]");     //valid     ( + sign is allowed)
		list.add("sharma+123@gmail.");     //invalid     ( after . there should be something like com, net etc)
		list.add("[email protected]");     //invalid       ( after @ sign keyword like gmail, yahoo missing)
		list.add("[email protected]");     //valid           (only numeric allowed)
		list.add("[email protected]"); 


		for (String email : list) {
			if (email.matches("^[_A-Za-z0-9-\\+]*@[a-zA-Z0-9]+(\\.[a-zA-Z]{2,})$")) {
				System.out.println("Valid email address : " + email);
			}
		}
	}
	       
}
Output:
Valid email address : [email protected]
Valid email address : [email protected]
Valid email address : [email protected]
Valid email address : [email protected]
Valid email address : [email protected]
Valid email address : [email protected]

Example 5:

We can extract some specific values out of the large text body as per the requirement. Let’s understand with the example.

In this example wee need to extract the words like book, movie, theater etc.

public class ExtractValueEx {

	public static void main(String[] args) {

		String str = "I like to read book and watching movie in theater.";
		Pattern p = Pattern.compile("(book|table|computer|movie|theater|TV)");
		
		Matcher m = p.matcher(str);
		
        while(m.find()){
        	System.out.println("Item found : "+m.group());
        }
	}	       
}
Output:
Item found : book
Item found : movie
Item found : theater

Example 6: 

We can replace or modify the required value in the text body as shown in the below example. We are changing the A’s EmpID.

public class ReplaceValueEx {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();

		String str = "A has EmpID=1234.B has EmpID=6789.";
		Pattern p = Pattern.compile("1234");
		
		Matcher m = p.matcher(str);
		StringBuffer bfr = new StringBuffer();
		
        while(m.find()){
        	m.appendReplacement(bfr, "3456");   // replace the id 1234 to 3456
        }
        m.appendTail(bfr);
        System.out.println(bfr);
	}	       
}
Output: A has EmpID=3456.B has EmpID=6789.

At some point of time, every programmer use regular expression.The complexity of regular expression may vary but with practice it will become easy to handle.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 14, 2015

    […] We will see the rest of the regular expression in the part 2. […]