Raj
Raj

Reputation: 487

Custom input filter accepts Numeric Value in regex

public class FilterActivity implements InputFilter {
Pattern pattern;

public FilterActivity(int beforeDecimal) {
    pattern=Pattern.compile("([0-9]{0,"+(beforeDecimal-1)+"})?");
}

@Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int spanstart, int spanend) {
    Matcher matcher=pattern.matcher(spanned);
    if(!matcher.matches()){
        return "";
    }
    return null;
}
}

When changing or editing the field it accepts a, 2a I need only accepts 0-9

editText.setFilters(new InputFilter[]{new FilterActivity(3)});

I know the property in android "number Decimal and number", but I try to achieve this problem using Regular expressions.

Upvotes: 0

Views: 964

Answers (2)

Heiko Finzel
Heiko Finzel

Reputation: 118

I agree with @horcrux but I think since your multiplier starts at 0, you can omit the "?":

"^([0-9]{0,"+(beforeDecimal-1)+"})$"

And if you don't need to catch the result, you can even omit the parentheses:

"^[0-9]{0,"+(beforeDecimal-1)+"}$"

But you will need the anchors (^ and $) to indicate, that there may be nothing to the left or right of the match.

@Raj if I understand your answer to @horcrux correctly then you have optional letters after the digit? try:

"^([0-9]{0,"+(beforeDecimal-1)+"}[a-z]?)$"

or:

"^([0-9]{0,"+(beforeDecimal-1)+"}[a-zA-Z]?)$"

if they can also be upper case

Upvotes: 1

akhilesh0707
akhilesh0707

Reputation: 6899

Try

    public class FilterActivity implements InputFilter {
      public FilterActivity(int beforeDecimal) { }

      @Override
      public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int spanstart, int spanend) {
           for (int i = start; i < end; i++) {
               if (!Character.isDigit(charSequence.charAt(i))) {
                     return "";
               }
            }
            return null;
     }
}

Upvotes: 0

Related Questions