Rakesh Rathod
Rakesh Rathod

Reputation: 21

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.

Upvotes: 1

Views: 1105

Answers (2)

amaurs
amaurs

Reputation: 1642

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.

Upvotes: 1

Anirudha
Anirudha

Reputation: 32807

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(.)..

Upvotes: 0

Related Questions