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.
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.
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.
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.
Therefore the following expression will work.
Below a little example showing how grouping regular expressions can assist you in replacing unknown Strings at runtime.
hahaa text to replacehaha haha a text to replace haha start hahaBlahaha end