$show=/label

Java String API replaceAll() Method Example

SHARE:

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


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.

COMMENTS

BLOGGER

About Us

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

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,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,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
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.
https://1.bp.blogspot.com/-meI3Kj_4iT8/XPUx-uPbnYI/AAAAAAAABo8/-pY4xh3Ztsc_iREKTYzcgmD7uzEGTyNCQCLcBGAs/s320/Java%2BString%2BAPI%2BreplaceAll%2528%2529%2BMethod%2BExample.PNG
https://1.bp.blogspot.com/-meI3Kj_4iT8/XPUx-uPbnYI/AAAAAAAABo8/-pY4xh3Ztsc_iREKTYzcgmD7uzEGTyNCQCLcBGAs/s72-c/Java%2BString%2BAPI%2BreplaceAll%2528%2529%2BMethod%2BExample.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/06/java-string-replaceall.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/06/java-string-replaceall.html
true
3124782013468838591
UTF-8
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