So much replace(Charsequence target, Charsequence Replacement) how much replaceAll(String regex, String Replacement) make substitution using matching patterns using regular expressions. The question that remains is: both of which replace(Charsequence target, Charsequence Replacement) how much replaceAll(String regex, String Replacement) use regular expressions, why only replaceAll(String regex, String Replacement) error for the same input? Note how such methods do this:
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(this)
.replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
The difference, as can be seen by their code, is the way in which the Pattern is creating. While replace(Charsequence target, Charsequence Replacement) uses Pattern.LITERAL
, that is, the input is roughly treated as normal characters and not a regular expression. For example, if replace(Charsequence target, Charsequence Replacement) were it so:
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString()).matcher(this)
.replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
We would also have problems with the entrance [ABCDEE+Calibri-11.04]
as regex, because it is not a valid regular expression and now we are not using a literal string, but a normal regular expression pattern.
Remember that it is not the way such methods treat the input and use regular expressions that is wrong, but rather the goal of each of them.
The suggestion then is to use a valid expression in replaceAll(String regex, String Replacement), as \[.+\]
, that will ensure the replacement of everything that has more than one character and is initiated by [
and ended with ]
, then something like that:
final String[] lines = new String[] {"[ABCDEE+Calibri-11.04]1 ", "[ABCDEE+Georgia,BoldItalic-9.0]Relação de poemas"};
Arrays.stream(lines).forEach(line -> System.out.println(line.replaceAll("\\[.+\\]", "")));
Would print this:
1
Relação de poemas
I thought replaceAll took a string like replace, I never stopped to think that in cases like:
String newStr = str.replaceAll("This", "That");
is also a regex. Thank you all.– Daniela Morais
Why are you disqualifying this question? Our friend needs help with regular expressions.!
– David Schrammel
@Danielamorais the problem and that the
replaceAll()
other thanreplace()
uses regular expressions, so your string should be"\\[ABCDEE\\+Georgia,BoldItalic-9.0\\]"
– David Schrammel
@Davidschrammel both use regular expressions, only that the
replace
uses literal Pattern. If the question is open (it was closed who knows why) I try to include an answer considering this different behavior– Bruno César