You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java.lang.String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replaceAll() function is a very useful, versatile, and powerful method and as a Java developer, you must know about it. Even though Java provides separate methods for replacing characters and replacing substring, you can do all that just by using this single method.
The replaceAll() method replaces each substring of this string (the String on which it is called) that matches the given regular expression with the given replacement. It internally uses classes like Pattern and Matcher from java.util.regex package for searching and replacing matching characters or substring.
Since String is immutable in Java it cannot be changed, hence this method returns a new modified String. If you want to use that String you must store it back on the relevant variable. Many developers forget to store the result of replaceAll() method back and think that the original String is modified, which is wrong and creates some of the most common but hard to find bugs in Java.
This concept is not just relevant for the replaceAll() method but other methods of java.lang.String class which does String manipulation e.g. trim(), split(), join() or concat() methods.
In this tutorial, I'll show you three examples of using the replaceAll() method in Java for replacing characters, substring, and using the regular expression for advanced find and replace tasks.
In the first example of replaceAll(), I have shown you how to replace all occurrences of a single character in String. This is also one of the common String coding questions but there you need to solve the problem without using the replaceAll() method.
Remember, even though replaceAll() allows you to replace a single character, you cannot pass a char value to this method as it expects String. As a workaround, you need to pass a single character String e.g. "a", "b" etc.
You should also remember, single quotes are used for character literals in Java and double quotes are used for String literals in Java e.g. 'a' is a char variable but "a" is a String variable.
In the second example of the replaceAll() method, I have shown you how to replace all occurrences of a substring in Java. Again it's simple just pass the target and replacement to the replaceAll() method, it is very similar to how you use the replace(CharSequence target, CharSequence replacement) method as demonstrated here.
The third one is the most interesting example, which replaces all whitespaces from String in Java.It uses a regular expression "\\s+" to convert String "Java is great" into "Javaisgreat". Since the first argument to the replaceAll() method is a regular expression String, it's possible to perform such a sophisticated find replace function in Java.
If you are curious about what does "\\s+" regex pattern does then here is a short explanation.
You can see from the output in the first example, character 'e' is successfully replaced by the letter 'a' and in the second example, substring "123" is replaced by "111", and in the third example, all whitespace is removed by replacing them with empty String.
If you want to learn more about regular expression and Java fundamentals, I suggest you joining these awesome core Java courses and books to understand basic concepts like this.
1) An invocation of this method of the form str.replaceAll(regex, replacement) yields exactly the same result as the expression
2) If the regular expression's syntax is invalid and the String.replaceAll() method throws PatternSyntaxException.
3) This method is available from Java 1.4 so you can use it on Java 5 as well.
4) Even though you can use the replaceAll() method to replace a single character or a substring, you should always pass a String to it. You cannot pass the character to it, that would be a compile-time error as shown below:
5) The first argument to this method is a regular expression String, so metacharacters have different meanings e.g. "\\s+" means to replace any whitespace up to any length.
That's all about how to use the replaceAll() method of java.lang.String class to replace characters and substring in Java. The most important thing to remember about the replaceAll() method is that it supports regular expression which allows you to perform sophisticated find and replace programmatically, much like how do you do in VI editor. If you want to learn more about the methods of String class, you can further join these online Java courses for beginners to learn with examples.
The replaceAll() method replaces each substring of this string (the String on which it is called) that matches the given regular expression with the given replacement. It internally uses classes like Pattern and Matcher from java.util.regex package for searching and replacing matching characters or substring.
Since String is immutable in Java it cannot be changed, hence this method returns a new modified String. If you want to use that String you must store it back on the relevant variable. Many developers forget to store the result of replaceAll() method back and think that the original String is modified, which is wrong and creates some of the most common but hard to find bugs in Java.
This concept is not just relevant for the replaceAll() method but other methods of java.lang.String class which does String manipulation e.g. trim(), split(), join() or concat() methods.
In this tutorial, I'll show you three examples of using the replaceAll() method in Java for replacing characters, substring, and using the regular expression for advanced find and replace tasks.
String replaceAll() Example in Java
Here is a sample Java program that will demonstrate how to use the replaceAll method in Java for replacing a single character, a substring, and using a regular expression for sophisticated find and replace, much like how you do in VI editor in Linux.In the first example of replaceAll(), I have shown you how to replace all occurrences of a single character in String. This is also one of the common String coding questions but there you need to solve the problem without using the replaceAll() method.
Remember, even though replaceAll() allows you to replace a single character, you cannot pass a char value to this method as it expects String. As a workaround, you need to pass a single character String e.g. "a", "b" etc.
You should also remember, single quotes are used for character literals in Java and double quotes are used for String literals in Java e.g. 'a' is a char variable but "a" is a String variable.
String bestseller = "clean code"; String alternative = bestseller.replaceAll("e", "a"); System.out.println("orginal string: " + bestseller); // print clean code System.out.println("replaced string: " + alternative); // print claan coda
In the second example of the replaceAll() method, I have shown you how to replace all occurrences of a substring in Java. Again it's simple just pass the target and replacement to the replaceAll() method, it is very similar to how you use the replace(CharSequence target, CharSequence replacement) method as demonstrated here.
String sample = "123 123 123 123 321"; String replaced = sample.replaceAll("123", "111"); System.out.println("orginal string: " + sample); // print 123 123 123 123 321 System.out.println("replaced string: " + replaced); // print 111 111 111 111 321
The third one is the most interesting example, which replaces all whitespaces from String in Java.It uses a regular expression "\\s+" to convert String "Java is great" into "Javaisgreat". Since the first argument to the replaceAll() method is a regular expression String, it's possible to perform such a sophisticated find replace function in Java.
// 3rd example - replacement using regular expression // the first argument you pass its regular expression // you can use this to replace all white space from // string as shown below String textWithWhitespace = "Java is great"; String changed = textWithWhitespace.replaceAll("\\s+", ""); System.out.println("orginal string: " + textWithWhitespace); System.out.println("replaced string: " + changed);
If you are curious about what does "\\s+" regex pattern does then here is a short explanation.
Java String replaceAll() Example
Here is our complete Java program, which includes all the three examples we have discussed above. You can write this program yourself and run it to see the result. You can further enhance this program by asking the user to enter input String and the character or substring to be replaced in command prompt. You can use a Scanner to read input from the command prompt and then use the same logic as discussed here for search and replace.public class Main { public static void main(String args[]) { // 1st example - replacing all occurrence of a character in String // you can replace single character but you cannot pass a char // to this replace() function, it expect a string, so you should // pass a single character string as shown below String bestseller = "clean code"; String alternative = bestseller.replaceAll("e", "a"); System.out.println("orginal string: " + bestseller); System.out.println("replaced string: " + alternative); // 2nd example - replacing all occurrence of a substring String sample = "123 123 123 123 321"; String replaced = sample.replaceAll("123", "111"); System.out.println("orginal string: " + sample); System.out.println("replaced string: " + replaced); // 3rd example - replacement using regular expression // the first argument you pass its regular expression // you can use this to replace all white space from // string as shown below String textWithWhitespace = "Java is great"; String changed = textWithWhitespace.replaceAll("\\s+", ""); System.out.println("orginal string: " + textWithWhitespace); System.out.println("replaced string: " + changed); } } Output original string: clean code replaced string: claan coda original string: 123 123 123 123 321 replaced string: 111 111 111 111 321 original string: Java is great replaced string: Javaisgreat
You can see from the output in the first example, character 'e' is successfully replaced by the letter 'a' and in the second example, substring "123" is replaced by "111", and in the third example, all whitespace is removed by replacing them with empty String.
If you want to learn more about regular expression and Java fundamentals, I suggest you joining these awesome core Java courses and books to understand basic concepts like this.
Important points about replaceAll() method
Here are some of the important things to know and remember about the String.replaceAll() method in Java:1) An invocation of this method of the form str.replaceAll(regex, replacement) yields exactly the same result as the expression
java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(replacement)
2) If the regular expression's syntax is invalid and the String.replaceAll() method throws PatternSyntaxException.
3) This method is available from Java 1.4 so you can use it on Java 5 as well.
4) Even though you can use the replaceAll() method to replace a single character or a substring, you should always pass a String to it. You cannot pass the character to it, that would be a compile-time error as shown below:
"string".replaceAll('t', 'd'); // compile time error
5) The first argument to this method is a regular expression String, so metacharacters have different meanings e.g. "\\s+" means to replace any whitespace up to any length.
That's all about how to use the replaceAll() method of java.lang.String class to replace characters and substring in Java. The most important thing to remember about the replaceAll() method is that it supports regular expression which allows you to perform sophisticated find and replace programmatically, much like how do you do in VI editor. If you want to learn more about the methods of String class, you can further join these online Java courses for beginners to learn with examples.
3 comments :
Hey Javin, I am David Brooks from www.javamockexams.com.
I really want to thank you for this post, I am going to share it on all my social media, if you do not mind.
I am really looking forward for more of these, to come soon.
If your audience is also interested in Java certification simulators, they can take a look here: http://clktr4ck.com/java
Thanks
David Brooks
IMHO, replaceAll should be used ONLY for regular expression as 1st param.
For replacing chars, or ordinary substrings, use the corresponding 'replace' methods - they are faster and safer.
1. replaceAll is very slow, because its internal use of Pattern and Matcher
2. if the 1st param is a string that comes from external sources and contains metacharacters, the result would be unexpected.
Hello @Annonymous, valid points, thanks for sharing this useful information with us.
Post a Comment