Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Signature
2.1.
Parameters 
2.2.
Return Value
2.3.
Exceptions
2.4.
Internal implementation
3.
Examples
4.
Frequently Asked Questions
4.1.
What are the different string substitution methods in Java?
4.2.
What are the different parameters passed to replaceAll() function?
4.3.
What are the possible exceptions in the replaceAll() function?
4.4.
What is the time complexity of replaceAll() function in java?
5.
Conclusion
Last Updated: Mar 27, 2024

Java String replaceall()

Author Akshit Mehra
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The String class looks at the individual characters in the sequence, compares the strings, searches for the strings, extracts the substrings, and makes a copy of the string with all the characters converted to upper or lower case. Includes methods for. Case mapping is based on the standard Unicode version specified in the Character class. The String class in Java has three types of substitution methods: 

  1. replace(): This method replaces the specified character with a new character each time it appears and returns a new string. You can use the String method Java Replace () to replace a set of character values.  
  2. replaceAll(): The Java String replaceAll () method finds all occurrences of the string that matches the regular expression and replaces it with replacement string. At the end of the call, the Java replaceAll () function returns a new string.  
  3. replaceFirst(): The Java string replaceFirst () method replaces only the first substring that matches the specified regular expression. String matching starts at the beginning of the string (from left to right). At the end of the call, the Java function replaceFirst () returns a new string.

 

In this blog, we will extensively discuss the java replaceAll() function.

Signature

public String replaceAll(regexp (Regular expression) , String replacement)

Parameters 

As we can see in the above signature, two parameters are being passed:

  1. regexp: The regular expression corresponding to the replacement required.
  2. String replacement: The replacement string which gets to replace the matching substring.

Return Value

The function returns a new string with characters being replaced.

Exceptions

The replaceAll() function returns:

  1. PatternSyntaxException: If the regular expression syntax passed is invalid, this exception is returned.

Internal implementation

Below is the internal implementation of the replaceAll() function:

public String replaceAll(String regex, String replacement) {  
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);  
} 
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

Below are certain examples which depicts the use of replaceAll() function:

  • Replacing Characters: Below is an example of replacing every occurrence of a single character.

    FileName: Example1.java
public class Example1{  
	public static void main(String args[]){  
		String s1="First example for replaceAll() function";  
		String replaceString=s1.replaceAll("e","a");
		//Above function will replace all the occurrences of "e" to "a"  
		System.out.println(replaceString);  
}}

 

Output: 

First axampla for raplacaAll() function

 

  • Replacing Words: Below is an example of replacing every word, or every set of words.

    FileName: Example2.java
public class Example2{  
	public static void main(String args[]){  
		String s1="Today is a holiday. Ram is watching TV.";  
		String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"  
		System.out.println(replaceString);  
}}  

 

Output:

Today was a holiday. Ram was watching TV.

 

  • Removing white spaces: Below is an example of removing white spaces from a given sentence using replaceAll() function.

    FileName: Example3.java
FileName: Example3.java
public class ReplaceAllExample3{  
	public static void main(String args[]){  
	String s1="Remove white spaces from the sentence.";  
	String replaceString=s1.replaceAll("\\s","");  
	System.out.println(replaceString);  
}}  

 

Output: 

Removewhitespacesfromthesentence.

 

  • Inserting white spaces: Below is an example of Inserting white spaces in a given sentence using replaceAll() function.

    FileName: Example4.java
public class Example4{  
	public static void main(String argvs[]){  
	String input_ = "Sentence";
	System.out.println(input_);  
	String regexp = "";  
	// Inserting white space before and after every character in the given input sentence.
	input_ = input_.replaceAll(regexp, " ");  
	System.out.println(input_); }  
}  

 

Output:

Sentence
S e n t e n c e

 

  • PatternSyntaxException: Below we see how replaceAll() function returns PatternSyntaxException when passed with incorrect regular expression.

    FileName: Example5.java
public class Example5{
	public static void main(String argvs[]){
	String str = "Below we see an exception.";  
	System.out.println(str);  
	String regex = "\\"; // Incorrect regexp (Regular expression) being passed.
	// Calling replaceAll() function now raises PatternSyntaxException.
	str = str.replaceAll(regex, "JavaTpoint ");  
	System.out.println(str); }  
}  

 

Output:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
at java.util.regex.Pattern.error(Pattern.java:1957)
at java.util.regex.Pattern.compile(Pattern.java:1704)
at java.util.regex.Pattern.(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.lang.String.replaceAll(String.java:2223)
at Example4.main(Example4.java:15)
Below we see an exception.

Frequently Asked Questions

What are the different string substitution methods in Java?

 The String class Java has three types of substitution methods: 

  1. replace (): This method replaces the specified character with a new character each time it appears and returns a new string. 
  2. replaceAll (): The Java String replaceAll () method finds all occurrences of the string that matches the regular expression and replaces it with the replacement string. 
  3. replaceFirst (): The Java string replaceFirst () method replaces only the first substring that matches the specified regular expression.

What are the different parameters passed to replaceAll() function?

While calling the replaceAll() function, we pass 2 parameters:

  1. regexp: The regular expression corresponding to the replacement required.
  2. String replacement: The replacement string which gets to replace the matching substring.

What are the possible exceptions in the replaceAll() function?

PatternSyntaxException is the exception that arises when the regular expression syntax passed is invalid.

What is the time complexity of replaceAll() function in java?

Each character in the input must be repeated at least once to replace all occurrences of the character. This is the complexity of O (n).

Conclusion

This article discussed the replaceAll() function offered by the String class in Java. We saw the signature of the function, along with its details, including parameters, exceptions thrown, etc. Further, we saw certain examples, which included replacing characters and words, and inserting and removing spaces using replaceAll() function. If you’d like to know more about Java, Check out our Java-Full stack course.

Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and get placed at your dream company. Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, System Design, Javascript, etc. Enrol in our courses, refer to the mock test and problems available, interview puzzles, and look at the interview bundle and interview experiences for placement preparations. We hope that this blog has helped you increase your knowledge regarding such DSA problems, and if you liked this blog, check other links. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass