Java.lang.String.replaceAll() Method
Advertisements
Description
The java.lang.String.replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement.
Declaration
Following is the declaration for java.lang.String.replaceAll() method
public String replaceAll(String regex, String replacement)
Parameters
regex -- This is the regular expression to which this string is to be matched.
replacement -- This is the string to be substituted for each match.
Return Value
This method returns the resulting string.
Exception
PatternSyntaxException -- if the regular expression's syntax is invalid.
Example
The following example shows the usage of java.lang.String.replaceAll() method.
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "!!Tutorials!!Point", str2;
String substr = "**", regex = "!!";
// prints string1
System.out.println("String = " + str1);
/* replaces each substring of this string that matches the given
regular expression with the given replacement */
str2 = str1.replaceAll(regex, substr);
System.out.println("After Replacing = " + str2);
}
}
Let us compile and run the above program, this will produce the following result:
String = !!Tutorials!!Point After Replacing = **Tutorials**Point