If you have to replace a String in some text based on a regular expression because you only know parts of the text to replace, grouping regular expressions becomes very handy.

Explanation

How to group regular expressions? Simple. Place round brackets around the groups of interest. In below example I want to replace the text in between the two Strings "haha".

"start hahaa text to replacehaha end"

In order to get the text of interest I first build a regular expression matching the whole String.

"haha.*?haha"

Using this regex I would only receive the full String including the embracing Strings, but I want to retrieve or replace only the unknown text in the middle. In above example "a text to replace".

Part of the solution is to group the different parts of the regular expression.

"(haha)(.*?)(haha)"

Now I can retrieve the different groups from a Matcher by looping through its group collection. For details see unit test below.

But since we want to replace the unknown part we have to either use String operations in combination with the group collection or we rely on the method replaceFirst in class Matcher.

This method replaces the first occurance of a match in a given text with a handed String. However, this alone does not do the trick. You can also rebuild a matched String by referencing the groups in a regular expression. This is a very nice feature, which makes it quite easy to replace unknown Strings of known pattern in Strings.

In order to reference a group from a Matchers current regular expression use the expression $n where n is a 1 based index / number. The index is one based as the group(0) returns the whole found match, in our example "hahaa text to replacehaha".

So now we use the refernces for groups to rebuild the String to replace to what we want.

For example in below unit test I want to see the following.

"hahaBlahaha"

Therefore the following expression will work.

1
match.replaceFirst("$1Bla$2");

Source Code

Below a little example showing how grouping regular expressions can assist you in replacing unknown Strings at runtime.

Unit Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testReplaceRegExGroup() {
	String src = "start hahaa text to replacehaha end";
	String regEx = "(haha)(.*?)(haha)";
	Pattern pattern = Pattern.compile(regEx);
	Matcher match = null;
 
	match = pattern.matcher(src);
	if (match.find()) {
		for (int i = 0; i <= match.groupCount(); i++) {
			System.out.println(match.group(i));
		}
	}
 
	System.out.println(match.replaceFirst("$1Bla$1"));
}

Output

hahaa text to replacehaha
haha
a text to replace
haha
start hahaBlahaha end