JavaRegular expressions

Replacing characters

Sometimes we need to replace a substring of a string with another string. Java provides several convenient methods to do that using regexular expressions.

The methods replaceFirst and replaceAll of a string

There are two methods of a string to do that:

  • String replaceFirst(String regex, String replacement) replaces the first occurrence of regex with replacement;
  • String replaceAll(String regex, String replacement) replaces all occurrences of regex with replacement;
where
  • regex — is a regular expression to which given string need to match;
  • replacement — the string that replaces a string that matches the regex (it is just a string, not a regex!).
Both methods return a new modified string because strings are immutable.

Be careful, the replace method also return a new modified string but it does NOT support regular expressions at all.

Let's look at examples below.
String digitRegex = "\\d"; // a regex to match a digit

String str = "ab73c80abc9"; // a string consisting of letters and digits

String result1 = str.replaceAll(digitRegex, "#"); // it replaces each digit with #

System.out.println(result1); // "ab##c##abc#"

String result2 = str.replaceFirst(digitRegex, "#"); // it replaces only the first digit with #

System.out.println(result2); // "ab#3c80abc9"

It is possible to use any regexes as the first argument of these methods. The following example demonstrates how to replace all sequences of upper-case Latin letters of a string with a single dash character.

String regex = "[A-Z]+";

String str = "aBoeQNmDFEFu";

String result = str.replaceAll(regex, "-"); // "a-oe-m-u"

The methods replaceFirst and replaceAll of a matcher

An object of Matcher has the two methods for replacing substring using a regex:

  • String replaceFirst(String replacement);
  • String replaceAll(String replacement).

They are similar to the same methods of a string, but these methods do not take regexes as their arguments, because any matcher has a regex. See an example below.

Pattern pattern = Pattern.compile("\\d"); // a regex to match a digit

String str = "ab73c80abc9"; // a string consisting of letters and digits

Matcher matcher = pattern.matcher(str);

System.out.println(matcher.replaceAll("#"));   // ab##c##abc#
System.out.println(matcher.replaceFirst("#")); // ab#3c80abc9

As you can see, the replacement works quite simple, the main is to write a correct regular expression.

How did you like the theory?
Report a typo