I’m doing some code maintenance at work, and I ran across this little snippet…
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
try {
if (!resultingTxt.matches("[0123456789]*[.]?[0123456789]{0,2}")||
Float.parseFloat(resultingTxt)>360f) {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString("");
return sp;
} else {
return "";
}
}
} catch (NumberFormatException nfe) {
// doesn't matter.
}
}
return null;
}
Now I am not a reg ex expert, but it seems to me like this is a very verbose way of checking if a text box is not empty, contains a number between 0 and 360, with no more than 2 decimal precision, and which doesn’t contain text. Am I missing something? This comes out of an android EditText.
Next part – Why in the name of the lord would you do this, rather than forcing the text to be number only, and using Double.parseDouble() or some equivalent? Is the regex that much faster that its worth it?
This code is a mess, so I wouldn’t be suprised if this guy had been reading – http://freeworld.thc.org/root/phun/unmaintain.html
You are correct in assuming that all the regex does is affirm that the input is a number, is not empty, and has no more than 2 decimal places.
No, there is no reason regex should be used in this place instead of
Double.parseDouble(). In fact, in a quick test I threw together, 10,000 iterations of the regex took ~5 times longer (348ms) than theDouble.parseDouble()format (71ms). Plus, he calls a parse on the number ANYWAY, to check if it’s> 360f. Why? Who knows.The coder here was either trying to get a job done quickly, or didn’t understand Java well. My guess is the latter, but I hope it was the former.
PS: That was an awesome link. Made my day. 🙂