Java - Regular Expression

> Procedural Languages > Java

1 - About

Regular Expression implementation in Java.

Regular expressions are managed within Java with the following classes:

  • Pattern to make from a string a pattern
  • Matcher to manage the matches

The class Pattern contains all details over how to create a regexp

2 - Articles Relatd

Advertising

3 - Characters

  • Escape:\\

4 - Snippet

String text = "$1 love $2";
Pattern pattern = Pattern.compile("(\\$([0-9]))");
// to catch $1 and $2
Matcher matcher = pattern.matcher(text);
System.out.println("There is "+matcher.groupCount()+" group in the pattern");
int matchCount = 0;
while (matcher.find()) {
	matchCount++;
	System.out.println("Value for the "+matchCount+" match");
	for (int i=0;i<=matcher.groupCount();i++) {
		System.out.println(" - Group "+i+": "+ matcher.group(i));
		if (i==0){
			System.out.println("  The group 0 represents always the whole expression");
		}
	}
}

Output:

There is 2 group in the pattern
Value for the 1 match
 - Group 0: $1
  The group 0 represents always the whole expression
 - Group 1: $1
 - Group 2: 1
Value for the 2 match
 - Group 0: $2
  The group 0 represents always the whole expression
 - Group 1: $2
 - Group 2: 2

5 - How to

6 - Documentation Reference

lang/java/regular_expression.txt · Last modified: 2017/10/23 16:25 by gerardnico