Example of String.replaceAll Method in Java

Java




// Java code to demonstrate the
// working of replaceAll()
 
public class rep2 {
    public static void main(String args[])
    {
        // Initialising String
        String Str = new String("Welcome to w3wiki");
 
        // original string
        System.out.print("Original String : ");
        System.out.println(Str);
 
        // Using replaceAll to replace regex with
        // replace_str
        System.out.print(
            "After replacing regex with replace_str : ");
        System.out.println(
            Str.replaceAll("(.*)geeks(.*)", "ASTHA TYAGI"));
    }
}


Output

Original String : Welcome to w3wiki
After replacing regex with replace_str : ASTHA TYAGI

Java String replaceAll() Method

The String replaceAll method in Java searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. Let us learn about Java replaceAll string method in this article. 

Similar Reads

Java String replaceAll()

This method replaces each substring of the string that matches the given regular expression with the given replace_str....

Example of String.replaceAll Method in Java

Java // Java code to demonstrate the // working of replaceAll()   public class rep2 {     public static void main(String args[])     {         // Initialising String         String Str = new String("Welcome to geeksforgeeks");           // original string         System.out.print("Original String : ");         System.out.println(Str);           // Using replaceAll to replace regex with         // replace_str         System.out.print(             "After replacing regex with replace_str : ");         System.out.println(             Str.replaceAll("(.*)geeks(.*)", "ASTHA TYAGI"));     } }...

Exceptions with String.replaceAll Java

...