What do the replaceAll () do in Java? - onlyxcodes

Sunday 7 July 2024

What do the replaceAll () do in Java?

In this tutorial, we will learn what the replaceAll () does in Java.


The String class in Java has a useful function called replaceAll() that is mostly used to replace each substring of a string that matches a given regular expression (regex) with a defined replacement string. This technique makes string conversions quick and flexible, especially helpful for jobs involving pattern matching and text modification.


replaceall() method in Java

Table Content

1. Method Signature

2. Return Value

3. Basic Usage

4. Advanced Usage

5. Handling Special Characters

6. Conclusion:


1. Method Signature

The replaceAll() method has the following signature:


public String replaceAll(String regex, String replacement)

Parameters:


  • regex: The string needs to match the regular expression.

  • replacement: The string that needs to be changed for every match.

2. Return Value

Returns a new string with the supplied replacement string appended to every instance of the regex in the original string.


3. Basic Usage

Example 1: Replacing Digits


Let's consider a simple example where we want to replace all digits in a string with a # character.


In this example:


  • \\d is a regex that matches any digit.

  • The replaceAll() method replaces each digit in the original string with #.

public class Test
{
    public static void main(String[] args) 
	{
        String originalString = "My phone number is 123-456-7890";
        String regex = "\\d";
        String replacement = "#";
        
        String result = originalString.replaceAll(regex, replacement);
        System.out.println(result);  // Output: My phone number is ###-###-####
    }
}

Output:


My phone number is ###-###-####

Example 2: Removing Whitespace


Another common use case is removing all whitespace from a string.


In this example:


  • \\s is a regex that matches any whitespace character.

  • The replaceAll() method removes all whitespace characters by replacing them with an empty string.

public class Test
{
    public static void main(String[] args) 
	{
        String originalString = "Hello World! This is a test.";
        String regex = "\\s";
        String replacement = "";
        
        String result = originalString.replaceAll(regex, replacement);
        System.out.println(result);  // Output: HelloWorld!Thisisatest.
    }
}

Output:


HelloWorld!Thisisatest.

4. Advanced Usage

Example 1: Replacing Words


More complex modifications, including changing entire words, can also be handled with the replaceAll() method.


In this example:


  • \\bcat\\b is a regex that matches "cat" as a whole word (bounded by word boundaries \\b).

  • The replaceAll() method replaces "cat" with "dog".

public class Test
{
    public static void main(String[] args) 
	{
        String originalString = "The cat sat on the mat.";
        String regex = "\\bcat\\b";
        String replacement = "dog";
        
        String result = originalString.replaceAll(regex, replacement);
        System.out.println(result);  // Output: The dog sat on the mat.
    }
}

Output:


The dog sat on the mat.

Example 2: Case-Insensitive Replacement


To perform case-insensitive replacements, you can use the (?i) flag in the regex.


In this example:


  • (?i) Java is a case-insensitive regex that matches "java" regardless of case.

  • The replaceAll() method replaces all case variations of "java" with "Python".

public class Test
{
    public static void main(String[] args) 
	{
        String originalString = "Java is Fun. I love java!";
        String regex = "(?i)java";
        String replacement = "Python";
        
        String result = originalString.replaceAll(regex, replacement);
        System.out.println(result);  // Output: Python is Fun. I love Python!
    }
}

Output:


Python is Fun. I love Python!

5. Handling Special Characters

Certain characters in the replacement string, like $ and \, have special impacts in regex replacements, thus they must be handled accordingly.


Example: Replacing with Dollar Sign


To include a dollar sign in the replacement, you need to escape it with a backslash.


In this example:


  • The replacement string \\$100 inserts a literal dollar sign followed by "100".

public class Test
{
    public static void main(String[] args) 
	{
        String originalString = "The price is 100 dollars.";
        String regex = "dollars";
        String replacement = "\\$100";
        
        String result = originalString.replaceAll(regex, replacement);
        System.out.println(result);  // Output: The price is 100 $100.
    }
}

Output:


The price is 100 $100.

6. Conclusion:

Java's replaceAll() function, which allows substring replacement based on regular expressions, is a flexible and effective tool for altering strings. Knowing how to use this technique can help you analyze and modify strings more effectively, whether you're doing basic replacements or complex text changes.


You may do a variety of text processing jobs with accuracy and ease by becoming familiar with replaceAll() and regular expressions.


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad