This tutorial explains how to create regular expressions in Java by using the Pattern and Matcher classes.
This tutorial can be realized with a simple text editor like « Notepad » or an IDE like « Eclipse » or « Netbeans». This tutorial requires some basic knowledge in Java.
Using the Pattern and Matcher classes
When we need to perform matches with performances, it is preferable to use two classes of the « java.util.regex » package: Pattern and Matcher.
The first class is used to compile the regex, the second is used to parse the String that we want to scan.
Compile the regex into a Pattern object
The first step is to call the static method « Pattern.compile() », passing in the regex. This method returns a Pattern object.
Pattern object is an internal representation of the pattern in a form that makes it efficient to perform matches.
Here is how to create the pattern:
Pattern patt = Pattern.compile("[0-9]+");
Construct a Matcher object
To check whether a particular string matches the pattern, we call the « matcher() » method on the « Pattern » object, passing in the string to match:
Matcher m = patt.matcher(str);
Parsing the string
For more information on how to use these objects to parse a string, you can read the tutorial that explains how to parse a string with the Matcher object.
You like this tutorial ?
Like this website in order to promote it on facebook !