简体   繁体   中英

Android - Regex to format the edittext as xxx.xx

I have taken some code from Limit Decimal Places in Android EditText .

The Regex is as given below. I have used "3" as digitsBeforeZero and "2" as digitsAfterZero .

mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?"); 

It works in all cases except xxx . When I try to enter the number " xxx.xx ", it does not allow me to enter the " dot (.) " after " xxx ".

Please help me to understand the Regex .

Your expression can be decomposed into parts to be explained better. Supposing you use

int digitsBeforeZero=3;
int digitsAfterZero=2; 

as you suggested, we have the expression:

"[0-9]{0,2}+((\\.[0-9]{0,1})?)||(\\.)?"

the first part you have a symbol that can be any digit, the part inside brackets is a quantifier it tells how many of the previous symbol are allowed, this case it will accept 0, 1 or 2 digits, the plus symbol is also a quantifier that stands for "one or more" but as there is no symbol before it it is not needed and just obscures the expression. Inside parenthesis you will find a group, this is used to match and retrieve specific matches from your expression you can read more on groups here . The expression inside the nested parenthesis will accept a '.' character followed by 1 or 0 digits and the question mark outside of the parenthesis means that the expression previous to it can be or not be in the string to match. Finally the '||' is an logic 'or' meaning that it will also match the expression after it. That expression will accept a '.' and it can be or not be present (the '?' quantifier) so it also matches an empty string.

If what you want is only to match strings like xxxx.yyyy with n 'x' and m 'y' this is a better aproach:

"[0-9]{0,"+n+"}(\\.[0-9]{0,"+m+"})?"

It is more clear, it will match an empty string as well, a single '.' however it will also match strings like "333." and ".33" so you have to tune it to your needs.

Remove -1 from both of your expressions..

With above expression you are actually trying to match 0 to 2 digits before decimal and 0 to 1 digit after decimal for your input 3,2 and hence its not allowing you to enter decimal point( . )..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM