Java String replaceAll Method

In Java programming, the replaceAll function is one of the string methods helpful to find and replacing each substring that matches the regular expression with a newly specified text. Replacing a text is one of the fundamental tasks in daily coding, and replaceAll() will do the trick for you and returns an entirely new string. For instance, after writing a document about the USA and you want to replace ‘usa’ with ‘USA’, you can use the replaceAll() function.

Generally, strings help store text information. The Java replaceAll() function provides various options for replacing a single character, multiple characters, or string pattern matching using regular expressions. You can find the required pattern and replace it with your own substring using this function.

This article will show you how to write string.repalceAll method in Java programming language, its syntax, parameters, and multiple examples.

Java String replaceAll Syntax

The Java Programming Language provides the replaceAll method to replace the matching substrings with a user-specified String. The replaceAll method accepts two string arguments. The first argument (regex) is the regular expression that represents a substring existing in the String_Object, and the second argument (Replacement) is the substring that you want to replace with.

public String replaceAll(String Regexp, String Replacement);

//To use in program
String_Object.replaceAll(Regexp, Replacement);

String_Object: Please specify the valid object to perform Replacement.

Replacement: Please specify the valid new one you want to insert into String_Object.

Regexp: Please specify the valid one we want to change or the regular expression representing the String. This Java replaceAll method will replace whatever you place here with a new string (Replacement).

The regex (regular expressions) argument is compelling. You can use it to look for complex patterns within the text.

  • \A: Beginning of the string.
  • \d: Matches the digits.
  • \D: To check for the non-digits.
  • \s: Matches the white Spaces.
  • \S: To find the non-whitespaces.
  • \w: Matches the Word characters.
  • \W: Matches the non-word characters.
  • \z: End of the string.

The Java replaceAll replaces the matched substring with a user-specified new string object. In the below Java program, we use the substring as the first argument. It may help to understand the basic functionality of the replaceAll method.

Java String replaceAll Example: Replace a Single Character

This section shows how to use the Java replaceAll() function to replace a specific character in a string. In this example, the original text str contains “a” in multiple locations. This function matches all the occurrences of the “a” and replaces them with “H”.

public class Simple {
	public static void main(String[] args) {
		String str = "Tutorials about a Programming";
			
		String reText = str.replaceAll("a", "H");

		System.out.println(reText);

	}
}
TutoriHls Hbout H ProgrHmming

replaceAll function to replace a word

Instead of replacing a single character, you can use this Java string replaceAll function to change the complete word or sentence.

public class Simple {
	public static void main(String[] args) {
		String str = "We are abc group working at abc company";
			
		String reText = str.replaceAll("abc", "MNC");
		String wrongText = str.replaceAll("abZ", "MNC");

		System.out.println(reText);
		System.out.println(wrongText);
	}
}
We are MNC group working at MNC company
We are abc group working at abc company

The following Java statement in this example looks for the “abc” word within the original text and replaces a whole term with the given substring (MNC).

 reText = str.replaceAll("abc", "MNC")

In the next line, we tried to replace the non-existing substring ‘abZ’ with the substring ‘MNC’. The above screenshot shows that it is not replacing anything (String_Object is unchanged).

wrongText = str.replaceAll("abZ", "MNC");

Lastly, we used the System.out.println statements to print the output.

Java String replaceAll function to replace multiple characters

This example uses the regex or regular expressions to find multiple characters, i.,e, a, and e, and replace them with a # symbol.

public class Simple {
	public static void main(String[] args) {
		String str = "we are abc working in abc companies";
			
		String reText = str.replaceAll("[ae]", "#");

		System.out.println(reText);
	}
}
w# #r# #bc working in #bc comp#ni#s

Java String replaceAll: Case-insensitive replacement

This function is case-sensitive by default, so it treats a differently from A. You must use the (?i) regular expression and the substring to achieve the case-insensitive replacement.

In the below example, we used (“(?i)t”, “A”) to instruct the replaceAll() function to search for both lower and uppercase t (regardless of case) and replace with A.

public class Simple {
	public static void main(String[] args) {
		String str = "Tutorial GaTeway Tweets";
			
		String reText = str.replaceAll("t", "A");
		String newText = str.replaceAll("(?i)t", "A");

		System.out.println(reText);
		System.out.println(newText);
	}
}
TuAorial GaTeway TweeAs
AuAorial GaAeway AweeAs

Java string replaceAll method to remove white spaces

In this example, ‘\ s’ help to identify the empty spaces within a given string, and we replace them with no space.

public class Simple {
	public static void main(String[] args) {
		String str = "Hi, hello. Welcome to You!";
			
		String reText = str.replaceAll("\\s", "");

		System.out.println(reText);
	}
}
Hi,hello.WelcometoYou!

How to add white spaces between characters?

It is straightforward “” identify each character and ” ” replace them with spaces.

public class Simple {
	public static void main(String[] args) {
		String str = "TutorialGateway";
			
		String reText = str.replaceAll("", " ");

		System.out.println(reText);
	}
}
 T u t o r i a l G a t e w a y

replaceAll to Remove non-digit Characters

In this example, ‘\ D’ helps to identify the non-digit characters within a given string, and we will use the Java replaceAll function to remove them.

public class Simple {
	public static void main(String[] args) {
		String strNum = "Hi 10, How 20 and 30 are doing!";
		String phNum = "(+91)987654321";
			
		String reText = strNum.replaceAll("\\D", "");
		String newText = phNum.replaceAll("\\D", "");

		System.out.println(reText);
		System.out.println(newText);
	}
}
102030
91987654321

Java String replaceAll regular Expressions Example

This program will help to understand the use of regular expressions in the Java string replaceAll method practically.

package StringFunctions;

public class ReplaceAllMethod2 {
	public static void main(String[] args) {
		String str = "We are abc working at Abc";
		String strd = "Hi 10, How 20 and 30 are doing!";
		
		String str2 = strd.replaceAll("[0-9]+", "");
		String str3 = strd.replaceAll(" [0-9]+", "");
		String str4 = str.replaceAll("[a-zA-Z]+", "Java");

		System.out.println("After Replacing First Sub String in str = " + str2);
		System.out.println("After Replacing Last Sub String in str = " + str3);
		System.out.println("After Replacing First Sub String in str1 = " + str4);
	}
}
Java String replaceAll Method 2

The following statement will call the replaceAll method to find the substring ‘[0-9]’ and replace it with the “”. It will replace the numbers between 0 and 9 with empty spaces.

str2 = strd.replaceAll("[0-9]+", "");

The above statement returns the output with extra spaces. So, we just altered the above statement to eliminate extra spaces.

str3 = strd.replaceAll(" [0-9]+", "");

The following String function statement will find the substring ‘[a-zA-Z]’ and replace it with “Java”. It will replace the alphabet between a and z, A and Z with Java.

str4 = str.replaceAll("[a-zA-Z]+", "Java");

If you use [^a-zA-Z0-9] regular expression in the above example, you can replace all the non-alphanumeric characters. Here, ^ informs the replaceAll function to replace any character not between a-z, A-Z, and 0-9.

Escape Characters in Java string replaceAll

In regular expressions, meta characters have a special meaning, so you can’t use them directly inside the replaceAll() function. The meta characters are “\ ^ $ . | ? + * [] {} ()”.

As we mentioned earlier, this function accepts regex as the first argument. So, to use the meta characters in the first argument, you have to escape these characters using \\.

In the below example, the original text strMeta contains a “symbol, i.e., a metacharacter. Because of this reason, we used \ to escape that character and replace each * with @ symbol.

public class Simple {
	public static void main(String[] args) {
		String strMeta = "Hi * Guys *, How * and * are * doing!";
			
		String reText = strMeta.replaceAll("\\*", "@");

		System.out.println(reText);
	}
}
Hi @ Guys @, How @ and @ are @ doing!

Comments are closed.