Advanced search and replace with replaceAll() and lambda expressions

You can use the Java replaceAll() method with a lambda expression to perform more advanced search and replace on strings. Specifically, we can use a lambda expression to allow dynamic replacement strings.

How to use a lambda expression to specify a dynamic replacement string

To specify a dynamic replacement string, we write a lambda expression that takes a MatchResult object as its input and returns a replacement string. Our expression can query the MatchResult to determine, e.g. the match position or matching substring, in order to determine the replacement string.

For example, the following code replaces the digits 0-9 in a string with their word equivalents:

String[] numerals = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

String str = "1 2 3 4";
Pattern pat = Pattern.compile("\\b\\d\\b");
Matcher m = pat.matcher(str);

str = m.replaceAll((match) -> {
  String noToReplace = match.group();
  int n = Integer.parseInt(noToReplace);
  return numerals[n];
});

In the above code, the match variable is a MatchResult object. (The type does not need to be specified in the arguments to a lambda expression, but it is defined by the replaceAll() method.)

In this example, the expression \b\d\b means "a digit surrounded by word breaks". Notice that we have used the MatchResult.group() method to query the entire substring matched (a digit which we then convert from string to integer using Integer.parseInt()), and from that we can decide which string replacement to use. If our regular expression contained capturing groups, we could also specify a group number. We can also call MatchResult.start() and MatchResult.end() to query the index of the start and end of the matching substring (with or without a capturing group number, as required).

Further information

The following related information is recommended:


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.