TL; DR
- if you need regex use
replaceAll or replaceFirst , - If you want your
target/replacement pair to be treated as literals, use replace (it also replaces the appearance of all your targets).
Most people confuse the bad name for replacement methods in the String class, which:
replaceAll(String, String)replaceFirst(String, String)replace(CharSequence, CharSequence)replace(char, char)
Since the replaceAll method explicitly states that it replaces all possible goals, people assume that the replace method does not guarantee this behavior, since it does not contain the suffix All .
But this assumption is incorrect.
The main difference between these methods is shown in this table:
βββββββββββββββββββββββ¦ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β replaced targets β β β βββββββββββββββββββββββββββββββββββββ¦βββββββββββββββββββββββββββββββ£ β β ALL found β ONLY FIRST found β β βββββββ¦βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ£ β β supported β replaceAll(String, String) β replaceFirst(String, String) β βregex β βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ£ βsyntaxβ not β replace(CharSequence, CharSequence)β \/ β β β supported β replace(char, char) β /\ β ββββββββ©βββββββββββββββ©βββββββββββββββββββββββββββββββββββββ©βββββββββββββββββββββββββββββββ
Now, if you do not need to use the regex syntax method, which does not expect it, but it treats target and replacement as literals.
So, instead of replaceAll(regex, replacement)
use replace(literal, replacement) .
As you can see, there are two overloaded versions of replace . Both of these should work for you, as they do not support regex syntax. The main difference between the two is as follows:
replace(char target, char replacement) just creates a new line and fills it with either the character from the source string or the character you decide to replace (depending on whether it was equal to the target character)
replace(CharSequence target, CharSequence replacement) is essentially equivalent to replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement.toString()) , which means it is the same as replaceAll , but (which means it is internally uses the regex mechanism), but it automatically executes the regular expression metacharacters used in target and replacement for
Pshemo
source share