jasdmystery
jasdmystery

Reputation: 1752

Regex/Input Filter for android to prevent more than one leading zero

I'm looking for some help to get a regex for Android, that prevents more that one leading zero in a given decimal number. Currently, any number of zeros can be added before the actual digit. I'm looking for the support of numbers like 0.1, 11.04, 0129 . The numbers that should not be allowed are .9, 0009999.33, 0007

Existing Filter Class, is given below :

public class DecimalDigitsInputFilter implements InputFilter{

Pattern mPattern;
int maxDigitsBeforeDecimalPoint = 10;
int maxDigitsAfterDecimalPoint = 2;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero)
{
    this.maxDigitsBeforeDecimalPoint = digitsBeforeZero;
    this.maxDigitsAfterDecimalPoint = digitsAfterZero;
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
        int dend)
{
    StringBuilder builder = new StringBuilder(dest);
    builder.replace(dstart, dend, source.subSequence(start, end).toString());
    if(!builder.toString().matches(
            "(([0-9]{1})([0-9]{0," + (maxDigitsBeforeDecimalPoint - 1) + "})?)?(\\.[0-9]{0,"
                    + maxDigitsAfterDecimalPoint + "})?"))
    {
        if(source.length() == 0)
            return dest.subSequence(dstart, dend);
        return "";
    }
    return null;
}}

Thanks in advance.

Upvotes: 4

Views: 1452

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626923

The regex that allows a float/integer number without 2 or more leading zeros:

^(?!0{2,})\d+(?:\.\d+)?$

See regex demo

Actually, it is suffice to check for just 2 0s in the beginning (although it is just a matter of taste):

^(?!0{2})\d+(?:\.\d+)?$
       ^

In Android, you can use the following regex declaration with matches():

String pattrn = "^(?!0{2,})\\d+(?:\\.\\d+)?";

See IDEONE demo

The regex breakdown:

  • ^(?!0{2,}) - at the beginning, checks if the next symbols are not 2 or more 0s
  • \\d+ - 1 or more digits
  • (?:\\.\\d+)? - 1 or 0 sequences of
    • \\. - a literal period
    • \\d+ - 1 or more digits

Upvotes: 0

Related Questions