Hello :D short question: What is the difference between
String geb = tf_datum.getText();
String sep = ""; //sep is short for seperator
geb = geb.replaceAll("\\.", sep);
geb = geb.replaceAll("\\,", sep);
geb = geb.replaceAll("\\-", sep);
geb = geb.replaceAll("\\ ", sep);`
and
String geb = tf_datum.getText();
String sep = "";
geb = geb.replaceAll("\\.", Matcher.quoteReplacement(sep));
geb = geb.replaceAll("\\,", Matcher.quoteReplacement(sep));
geb = geb.replaceAll("\\-", Matcher.quoteReplacement(sep));
geb = geb.replaceAll("\\ ", Matcher.quoteReplacement(sep));
Because both is functionating. I tried to understand each method (in the second one) and to put it together but it makes no sense. If somebody can help me, that would be very nice! Thanks. :) (and I also found the other question which seems to be the same, but he did not use the Matcher.quote inside of the replaceAll() ... so I was not shure if it is the same)
In the Matcher
case, you are doing some extra work that is not necessary, but it still effectively does the same thing (but I would assume you pay an efficiency price, though it would be negligible in this case).
In the first case, you do geb.replaceAll("\\.", "")
. So you are saying take geb
, and replace every period with 'nothing' essentially.
In the second case, you do geb.replaceAll("\\.", Matcher.quoteReplacement(sep))
. Now, you are saying, take geb
and replace every period with the return value of Matcher.quoteReplacement("")
. In this case, Matcher.quoteReplacement
returns ""
, exactly what you put into it. So it is essentially an extra/useless call that is not needed. Take a look at the docs for Matcher.quoteReplacement
here.
And for String.replaceAll
here.
The one thing it does mention here though is to use quoteReplacement
to suppress the special meaning of control characters like "\"
and "$"
. So you only need to use that if you want the replacement String
(the second argument to replaceAll
) to behave as if those are literal characters and not control characters.
Also of note, you can do this all in one regex like geb.replaceAll("[\\-\\,\\.\\s]", "");
. I think there are even better ways than that to do it but my regex isn't great.