.replaceAll()
The String
class’ .replaceAll()
method replaces every matching subsequence in the input sequence with the specified replacement string.
Syntax
string.replaceAll(String regex, String repl);
regex
represents the regular expression: a set of special characters and letters used for matching specific text.
repl
represents the string to be substituted for each match.
Note: It’s important to note that certain characters in the replacement string, such as backslashes and dollar signs ($), may have special meanings, so it’s recommended to use
Matcher.quoteReplacement(String)
to prevent these characters from affecting the results.Note: Both the
.replace()
and.replaceAll()
methods replace all occurrences of a matching string and acceptCharSequence
as input. However, the key difference is that.replaceAll()
treats the givenCharSequence
as a regular expression and searches forregex
matches, while.replace()
treats the input as plain text.
Example
The example below removes all whitespace:
public class Main {public static void main(String[] args) {String myString = "Dog\t \r\rComputer\n\n \r House \t Yes \n ";String regex = "\\s";// The shorthand code \s represents spaces, tabs, and newline charactersString replacement = "";String newString = myString.replaceAll(regex, replacement);System.out.println(newString);
This results in the following output:
DogComputerHouseYes