The String.replaceAll(regex, replacement) in Java replaces all occurrences of a substring matching the specified regular expression with the replacement string.
A similar method replace(substring, replacement) is used for matching the literal strings, while replaceAll() matches the regex. Note that in regular expressions, literal strings are also patterns, so replaceAll() will work with literal strings as well, in addition to regex patterns.
1. String.replaceAll() API
The syntax of the replaceAll() API is as follows:
String updatedString = thisString.replaceAll(regex, replacement);
- thisString: the string that should be searched for substring pattern and modified.
- regex: pattern to be searched.
- replacement: each occurrence of the matches will be replaced with this substring.
- updatedString: the result of the API that is the modified string.
2. String.replaceAll() Example
The following Java program demonstrates the usage of replaceAll() API.
2.1. Replace All Occurrences of a Word
The following Java program replaces all occurrences of “java” with “scala“.
String str = "how to do in java !! a java blog !!";
Assertions.assertEquals("how to do in scala !! a scala blog !!", str.replaceAll("java", "scala"));
2.2. Remove All Whitespaces
The following Java program replaces all occurrences of whitespaces in a string with an empty string.
String blog = "how to do in java";
Assertions.assertEquals("howtodoinjava", blog.replaceAll("\\s", ""));
3. PatternSyntaxException
We should know that replaceAll() throws PatternSyntaxException
if the regex’s syntax is NOT valid. In the given example, “[” is an invalid regular expression, so we get the exception in runtime.
Assertions.assertThrows(PatternSyntaxException.class, () -> {
blog.replaceAll("[", "");
});
Happy Learning !!
References: String Java Doc
Leave a Reply