In this java tutorial we will learn to use regular expression in java.Regular expression is very powerful tool for text manipulation and searching.It provides the fastest searching in huge amount of available data.So if you know it definitely you will save a lot time while doing these operations.In this tutorial I am going to describe how to use regular expression in java,I will not teach you the regular expression(If you are new to regular expression then please update yourself first via techcresendo.com)
In java we have java.util.regex package for regular expressions.This package basically contains three classes
- Pattern: This class represents the pattern in regular expression.Pattern is basically a format of text which needs to be matched in a group of texts.Patterns are constructed using regular expressions. e.g pattern
"[tT]rue" matches true or True
- Create a pattern object.This object defines your regular expression. Pattern pattern=Pattern.compile(“regex”);
- Now with the help of Pattern object we can get Matcher object for a given input text(into which pattern to be matched). Matcher matcher=pattern.matcher(INPUT_TEXT);
- Now using this matcher object we can easily find the pattern in the text as we will see in the example program.
package com.techy.rajeev; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternMatch { public static final String INPUT_TEXT = "This is a test for regular expression Testing."; public static final String PATTERN = "[tT]est"; public static void main(String[] args) { Pattern pattern = Pattern.compile(PATTERN); Matcher matcher = pattern.matcher(INPUT_TEXT); while (matcher.find()) { System.out.print("Start pos: " + matcher.start()); System.out.print(" End pos: " + matcher.end() + " "); System.out.println(matcher.group()); } } }
Output:
Start pos: 10 End pos: 14 test
Start pos: 38 End pos: 42 Test
Read More ->>