Java String API replaceAll() Method Example


Java-W3schools Blog. Quick guide to Java String API replaceAll() Method Example. Replaces all occurrences if the given regular expression pattern matches.

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


The resulting String

1.4 Throws


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);


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);


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");


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.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java String API replaceAll() Method Example
Java String API replaceAll() Method Example
Java-W3schools Blog. Quick guide to Java String API replaceAll() Method Example. Replaces all occurrences if the given regular expression pattern matches.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content