Saturday, March 26, 2011

Java Regular Expressions

Today I want to provide some useful information about the use of regular expressions in Java.

Regular expressions handling is part of the Java library, adding to the vast functionality already offered by it. In short, we could say that regular expressions represent string patterns

They have may uses. For instance, they can be used to filter the files in a directory whose name follows a particular pattern.

The good news about Java and regular expressions, is that the API is pretty simple (something that can not be said about other APIs in the standard library). It is based in the use of two classes, the Pattern and the Matcher. Obviously the Pattern class represents the regular expression pattern, while the Matcher applies the regular expression to a particular String.

There are three ways to use a Matcher:
  1. To find substrings matching the pattern
  2. To check in the whole input string matches the pattern
  3. To check if a defined region within the inputs string matches the pattern

More information can be found in the Java Regular Expressions Trail.

The following code snippet shows how to use a Pattern and a Matcher to filter Strings in an array. It uses the Matcher to check if the whole input matches the pattern. The source code can be edited and downloaded from IDEONE.COM:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;
import java.lang.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Initializing");
String input[] = {"pattern0_1","pattern1_2","pattern_d"};
Pattern p = Pattern.compile("(pattern)(\\d+)(_)(\\d)+");
for(int i = 0 ; i < input.length ; i++){
Matcher m = p.matcher(input[i]);
if(m.matches()){
System.out.println(m.group());
}
}
}
}

Enjoy!!!