Java - Regexp

> Procedural Languages > Java

1 - About

3 - Concept

3.1 - Group

Regular Expression - Group (Capture|Substitution)

Capturing groups are numbered by counting their opening parentheses from left to right.

Example: expression ((A)(B(C))) are four such groups:

  • 1: ((A)(B(C)))
  • 2: (A)
  • 3: (B(C))
  • 4: (C)
Pattern pattern = Pattern.compile("((A)(B(C)))");
Matcher matcher = pattern.matcher("myInputString");
Assert.assertEquals("There is 4 groups in this pattern", 4, matcher.groupCount());
Advertising

3.2 - Iterate

Example on how to iterate over the pattern matches.

String sourceText = "ABC";
Pattern pattern = Pattern.compile("((A)(B(C)))");
Matcher matcher = pattern.matcher(sourceText);
 
// Number of find
Integer seqCounter = 1;
// Matcher try to find the first sequence match
while (matcher.find()) {
 
	seqCounter++;
 
	System.out.println();
	System.out.println("Sequence " + seqCounter);
 
	for (int i = 0; i <= matcher.groupCount(); i++) {
 
		System.out.printf(i + " : " + matcher.group(i));
		if (i == 0) {
			System.out.printf(" (the index 0 contains the whole string that matches)\n");
		} else {
			System.out.printf("\n");
		}
	}
 
}
Sequence 2
0 : ABC (the index 0 contains the whole string that matches)
1 : ABC
2 : A
3 : BC
4 : C
lang/java/regexp.txt · Last modified: 2018/10/26 09:24 by gerardnico