1

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.

Community
  • 1
  • 1
Rakesh Rathod
  • 21
  • 1
  • 4

2 Answers2

1

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.

amaurs
  • 1,622
  • 1
  • 13
  • 18
0

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

Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • I have removed -1 but It allows me to enter 4 digits before decimal point. I want to allow only 3 digits before decimal point. Please help me to prepare the regex for xxx.xx number – Rakesh Rathod Jul 11 '13 at 16:10