Table of contents
1.
Introduction
2.
Signature
2.1.
Parameters 
2.2.
Return Value
2.3.
Exceptions
2.4.
Internal implementation
3.
Examples
3.1.
Java
3.2.
Java
3.3.
Java
3.4.
Java
3.5.
Java
4.
String replace() Method in Java
4.1.
Examples
4.1.1.
Replacing Characters:
4.1.2.
Replacing Substrings:
4.1.3.
Case Sensitivity Demonstration:
4.1.4.
Replacing Digits (Masking):
5.
Frequently Asked Questions
5.1.
How to use String replace() in Java?
5.2.
How to use replaceAll()?
5.3.
How to replace string parts in Java?
6.
Conclusion
Last Updated: Nov 29, 2024

Java String replaceall()

Author Akshit Mehra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.
String replaceall()

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

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
  • Java

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); 
}}
You can also try this code with Online Java Compiler
Run Code

Output: 

First axampla for raplacaAll() function

 

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

    FileName: Example2.java
  • Java

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); 
}} 
You can also try this code with Online Java Compiler
Run Code

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
  • Java

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); 
}}
You can also try this code with Online Java Compiler
Run Code

Output: 

Removewhitespacesfromthesentence.

 

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

    FileName: Example4.java
  • Java

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_); } 
You can also try this code with Online Java Compiler
Run Code

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
  • Java

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); } 
You can also try this code with Online Java Compiler
Run Code

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.

String replace() Method in Java

The replace() method in Java is used to replace all occurrences of a specific character or substring in a string with another character or substring. It creates a new string since strings in Java are immutable.

1. Method Variants:

The replace() method has two main variants:

  • replace(char oldChar, char newChar): Replaces all occurrences of a character with another character.
  • replace(CharSequence target, CharSequence replacement): Replaces all occurrences of a substring with another substring.

2. Immutable Strings:

The method doesn’t modify the original string but creates a new string with the replacements.

3. Case Sensitivity:

The replace() method is case-sensitive. For example, replacing 'a' will not affect 'A'.

4. NullPointerException Risk:

If the original string or any parameter (e.g., target) is null, the method will throw a NullPointerException.

5. Use Cases:

  • Correcting typos in a string.
  • Masking or replacing sensitive information (e.g., replacing digits in credit card numbers with *).
  • Formatting strings.

Examples

Replacing Characters:

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "hello world";
        String result = str.replace('o', 'a'); // Replace 'o' with 'a'
        System.out.println(result); // Output: hella warld
    }
}

Replacing Substrings:

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "I like apples. Apples are sweet.";
        String result = str.replace("apples", "bananas"); // Replace "apples" with "bananas"
        System.out.println(result); // Output: I like bananas. Apples are sweet.
    }
}

Case Sensitivity Demonstration:

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "Java is Fun. JAVA is Powerful.";
        String result = str.replace("JAVA", "Python"); // Case-sensitive
        System.out.println(result); // Output: Java is Fun. Python is Powerful.
    }
}

Replacing Digits (Masking):

public class ReplaceExample {
    public static void main(String[] args) {
        String cardNumber = "1234-5678-9876-5432";
        String masked = cardNumber.replace("5678", "****");
        System.out.println(masked); // Output: 1234-****-9876-5432
    }
}

Frequently Asked Questions

How to use String replace() in Java?

Use replace() to replace characters or substrings in a string, e.g., str.replace('a', 'b') or str.replace("old", "new").

How to use replaceAll()?

Use replaceAll() to replace substrings matching a regular expression, e.g., str.replaceAll("\\d", "*") replaces all digits with *.

How to replace string parts in Java?

Use replace() or replaceAll() to replace specific parts of a string. For case-insensitive replacement, combine with Pattern and Matcher.

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 Code360 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.

Live masterclass