regex - Android TextWatcher decimal numbers -


i'm trying create regular expression, find that: 1 ; 12 ; 12,4 ; 12,45 ; 12.4 ; 12.45 (numbers can different ofc).

that's regex regex: ^[0-9]?[0-9]?[,.]?[0-9]?[0-9]?$, passes e.g. 1234, don't want this.

i want create edittext textwatcher, filtrate text regex.

my code:

textwatcher discounttextwatcher = new textwatcher() {     private final pattern spattern = pattern.compile("^[0-9]?[0-9]?[,.]?[0-9]?[0-9]?$");          private charsequence mtext = "";          private boolean isvalid(charsequence s) {             return spattern.matcher(s).matches();         }          @override         public void ontextchanged(charsequence s, int start, int before, int count){          }          @override         public void beforetextchanged(charsequence s, int start, int count,                                       int after){             mtext = isvalid(s) ? s : mtext;         }          @override         public void aftertextchanged(editable s)         {             if (!isvalid(s) || s.length() > 4)             {                 adddocumentdiscountvalue.removetextchangedlistener(this);                 adddocumentdiscountvalue.settext(mtext);                 adddocumentdiscountvalue.setselection(mtext.length());                 adddocumentdiscountvalue.addtextchangedlistener(this);             }         }     }; 

edit:

now i've got better regex (thanks @nu11p01n73r) still doesn't work. can't write colon after 2 numbers, dunno why. that's strange, three numbers in row works...

problem regex

the mistake made made every character class optional.

so regex engine try fool eliminating classes doesn't need match

that when give input

1234 

the regex engine safely ignore character clas [,.] can match input, because gave them optional.

how ^[0-9]?[0-9]?[,.]?[0-9]?[0-9]?$ matches 1234

1234 | [0-9]? #first optional  1234  | [0-9]? #second optional  1234   |   here next patern [,.]. regex engine cannot match pattern input. since optional, forgets moment such pettern there ;)  1234   |  [0-9]? # third optional  1234    |  [0-9]? #frourth optional  1234     |     $ end of input. successfull match 

solution

/^[0-9]{1,2}([.,][0-9]{1,2})?$/ 

regex demo


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -