Last Updated:

Example of using the replaceAll method in Java: How to replace part of a string?

method in Java
 

The replaceAll method. Theory

The String class in Java provides methods for creating and manipulating strings. The String class already has many ready-made methods, for example, for subtracting strings using substring(),comparing parts of strings using the regionMatches() method, the length of a particular string, specifying the format of a string, searching for substrings, and much more. Learn more about the String class and working with strings here.

Use the replaceAll() method to replace all occurrences of a substring with a regular expression. The syntax for the replaceAll() method is as follows:

These two parameters mean the following:

  1. regex is a regular expression that specifies what will be replaced
  2. replacement is the line to be replaced

To simplify, in the first parameter you define what you want to replace with the second parameter. In this case, the first parameter can have both a string and a regular expression.

Important points when using replaceAll

  • Be careful when using the replaceAll method with a regular expression, because if there is an error in the regular expression syntax, it can throw a PatternSyntaxException.
  • When you use the replaceAll method, the value of the existing string is not changed, instead a new object is created to store the new value.
  • The replaceAll() method is case sensitive, which means that it distinguishes between uppercase characters and their lowercase equivalents.

Example of using the replaceAll method

Consider a simple program for replacing letters in a string with other letters and strings:

The following is an example of using the replaceAll method in Java with regular enemy:

For more information about other methods of handling strings in Java, see Working with Strings in Java.