Both replace (CharSequence target, CharSequence replacement) replaceAll (String regex, String replacement) makes overriding using matching of patterns using regular expressions. The question that remains is: both replace (CharSequence target, CharSequence replacement) replaceAll (String regex, String replacement) use regular expressions, because only replaceAll (String regex, String replacement) gives error for same entry ? Notice how these 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 from their code, is how Pattern is creating. While replace ( CharSequence target, CharSequence replacement) uses Pattern.LITERAL
, that is, roughly the input is treated as normal characters and not a regular expression. For example, if replace (CharSequence target, CharSequence replacement) :
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 [ABCDEE+Calibri-11.04]
entry as regex , since it is not a valid regular expression and now we are not using a literal string but a normal regular expression pattern.
It's worth noting that it's not the way these methods handle input and use regular expressions that are wrong, but rather the purpose of each.
The suggestion is then to use a valid expression in replaceAll (String regex, String replacement) , as \[.+\]
, that will guarantee the replacement of everything that is more than one character and is started by [
and finished with ]
, then something like this:
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