Since Java 9 we can use a function as argument for the Matcher.replaceAll
method. The function is invoked with a single argument of type MatchResult
and must return a String
value. The MatchResult
object contains a found match we can get using the group
method. If there are capturing groups in the regular expression used for replacing a value we can use group
method with the capturing group index as argument.
In the following example we use the replaceAll
method and we use a regular expression without and with capturing groups:
package mrhaki.pattern; import java.util.function.Function; import java.util.regex.MatchResult; import java.util.regex.Pattern; public class Replace { public static void main(String[] args) { // Define a pattern to find text between brackets. Pattern admonition = Pattern.compile("\\[\\w+\\]"); // Sample text. String text = "[note] Pay attention. [info] Read more."; // Function to turn a found result for regular expression to upper case. Function<MatchResult, String> bigAdmonition = match -> match.group().toUpperCase(); assert admonition.matcher(text).replaceAll(bigAdmonition).equals("[NOTE] Pay attention. [INFO] Read more."); // Pattern for capturing numbers from string like: run20=390ms. Pattern boundaries = Pattern.compile("run(\\d+)=(\\d+)ms"); // Function to calculate seconds from milliseconds. Function<MatchResult, String> runResult = match -> { double time = Double.parseDouble(match.group(2)); return "Execution " + match.group(1) + " took " + (time / 1000) + " seconds."; }; assert boundaries.matcher("run20=390ms").replaceAll(runResult).equals("Execution 20 took 0.39 seconds."); } }
Written with Java 14.