The mandate
Create regular expressions in Java

Create regular expressions in Java

Category: Programming.
Posted by on the 23/04/2014.
Last update on the 23/04/2014.

   Next tutorial>>


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 !

   Next tutorial>>

You like this tutorial ? Share it with your friends !
Partager sur Facebook Partager sur Twitter Partager sur Myspace Partager sur Stumbleupon Soumettre sur Reddit Partager sur Digg Ajouter à vos favoris Technorati Ajouter à vos favoris Live Ajouter à vos favoris Google Ajouter sur vos favoris Yahoo