Java String API replaceAll() Method Example

1. String replaceAll() Overview


In this tutorial, We'll learn about Java String API replaceAll() Method with Example (String.replaceAll).

As name "replaceAll" suggests, It replaces each substring of this string that matches the given regular expression with the given replacement. Refer the below syntax, it takes regex which is a regular expression pattern.

This method is a instance method which should be invoked on a string. If this string has a pattern then it replaces all matched pattern's with the second parameter value.

In the previous article,  discussed on String replace() method with examples.

Java String API replaceAll() Method Example


1.1 Syntax


public String replaceAll​(String regex, String replacement)

1.2 Parameters


regex - the regular expression to which this string is to be matched
replacement - the string to be substituted for each match

1.3 Returns


String 

The resulting String

1.4 Throws


PatternSyntaxException

if the regular expression's syntax is invalid

1.5 Since


java 1.4 version



2. String replaceAll() Method Example


We'll write a program to replace "Java 8" with Java 12 using replaceAll method. This method takes two parameter. We should pass regex to the first parameter and replacement string in the second parameter.

2.1 Replacing all matches with a new String


String str1 = "Welcome to Java 8. We are learning Java 8 String API now.";
String replacedNewString = str1.replaceAll("Java 8", "Java 12");
System.out.println("replaceAll method output: " + replacedNewString);

Output:

replaceAll method output: Welcome to Java 12. We are learning Java 12 String API now.

Let us take a look at output. Java 8 is present twice in the input string but after invoking replaceAll method, it is replaced all to Java 12.

2.2 Replacing white spaces with hyphen(-)


Now, will give input a sentence which has spaces in it. Our program need to remove all white spaces using regular expression and replace with hyphen (-) symbol.

Refer the below code.

String str2 = "Welcome to java w3schools blog";
String replacedNewString2 = str2.replaceAll("\\s", "-");
System.out.println("After removing white spaces : " + replacedNewString2);


Output:

This code will find all blank spaces and replaces with - symbol.

After removing white spaces : Welcome-to-java-w3schools-blog

3. String replaceAll() throws PatternSyntaxException


There is a case where it throws run-time exception using replaceAll method. This method expects to get a valid regular expression. If we don't pass a valid one then will get PatternSyntaxException.

We'll simulate the program to throw this exception.

str2.replaceAll("[^*^", "Invalid");

Output:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 3
[^*^
^
at java.base/java.util.regex.Pattern.error(Pattern.java:2015)
at java.base/java.util.regex.Pattern.clazz(Pattern.java:2683)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2126)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2056)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1778)
at java.base/java.util.regex.Pattern.(Pattern.java:1427)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.replaceAll(String.java:2135)
at com.java.w3schools.blog.string.StringReplaceAllExample.main(StringReplaceAllExample.java:21)

Because, We have imputed a invalid regex.


4. replaceAll() Internal Code


This method is implemented in simple way to understand. See the internal implementation code as described below.

public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}


Step 1: First calls Pattern.compile(regex) by passing given regex. compile() method parses the given regex and checks valid or not. If invalid then will throw PatternSyntaxException.

Step 2:
Next calls Pattern.matcher(this) method will find the matches in the string with given regex pattern. Then, it will return Matcher instance.

Step 3: It calls replaceAll(replacement) on matcher instance. This method replaces all occurrences of matches if any. replaceAll of Matcher class, internally creates StringBuffer and appends all replaced and original strings into it. Finally, converts StringBuffer into String and returns it.

5. Conclusion


In this tutorial, We've seen how to use java string api replaceAll method and what this method does.

And Examined with example program on it to replace all white spaces with hyphen using a valid regular expression. If regex is invalid then will throw run time exception saying PatternSyntaxException.

Further more explained about how replaceAll method works internally and how it is implemented.

Example code snippets shown in this article is available over GitHub.

0 Comments