Alan Alan - 10 months ago 119
Android Question

Input Filter - Regex for Two Decimals

I am trying to create a regex for my

to only allow input that is in dollar format. However it is not working.

public class DecimalInputFilter implements InputFilter {

Pattern mPattern;

public DecimalInputFilter() {

public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

Matcher matcher=mPattern.matcher(dest);
return "";
return null;


The Regex thought process -

  • At least one numeric character

  • a dot followed by exactly two numeric characters (Optional)

When I try to apply this, it does not allow me to input any numbers. What am I missing?

Answer Source

Whatever you type in the editText, you receive the CharSequence in source, and your already entered string in dest, so instead try

Matcher matcher=mPattern.matcher(dest.toString() + source.toString());

and use the regex as ^[0-9]+([.][0-9]{0,2})?$

The above regex is also going to except 4. but nothing can be done as we can enter only one char at a time, so to take care of that you can put a final regex check after submitting the value.