Java String ReplaceAll Method Example

In this example we shall explain the replaceAll() method in the String class. With the replaceAll() method we can replace the whole or part of the string or character sequences. String objects are immutable and cannot be changed the value. When ever you change the value, new string object is created. This method also creates the new object after replacing the values and return the new object. Lets look at the below example to understand this concept better. Some of the operations you can do using the replaceAll() method is:

  1. You can replace the single character
  2. You can replace the sequence of characters or a word
  3. You can replace using the regular expression


 * String replaceAll() method example
 * @author krishna
public class StringReplaceExample {
	public static void main(String args[]){
		String str = "String replaceAll() method example!!";
		String strRegExTest = "Java 12 23 String 4 Replace Example";
		String strObj = null;

		// Replace all occurrences of "t" to "T"
		strObj = str.replaceAll("t", "T");

		// Remove all occurrences of "!"
		strObj = str.replaceAll("!", "");

		// Replace "example" to "Example"
		strObj = str.replaceAll("example", "Example");

		// Remove all the numbers
		strObj = strRegExTest.replaceAll("[0-9]+", "");

		// Replace all the words to "Word"
		strObj = strRegExTest.replaceAll("[a-zA-Z]+", "Word");



STring replaceAll() meThod example!!
String replaceAll() method example
String replaceAll() method Example!!
Java   String  Replace Example
Word 12 23 Word 4 Word Word

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!