Reputation: 38695
Hi I used this regex for validate number with decimal separator and thousand separator
ets = "\\,";
eds = "\\.";
"^([+\\-]?[0-9" + ets + "]*(" + eds + "[0-9]*)?)$"
But this fail
(it accept when it should not) for two of my unit test case,
12.
, and 1,,2
, anyone can help please?
Note: This work for 1..2
.
Upvotes: 3
Views: 2721
Reputation: 85478
Let's look at the actual regex that is used:
^([+\-]?[0-9\,]*(\.[0-9]*)?)$
This matches 12.
because your second part is (\.[0-9]*)
. Note that *
means zero or more, so digits are optional.
This also matches 1,,2
because you included the comma in the first character class [0-9\,]
. So actually your regex would match ,,,,,,,,
as well.
This can be solved without regexes, but if you need a regex, you'd probably want something like this:
^[+-]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$
Broken down:
^ # match start of string
[+-]? # matches optional + or - sign
[0-9]{1,3} # match one or more digits
(,[0-9]{3})* # match zero or more groups of comma plus three digits
(\. # match literal dot
[0-9]+ # match one or more digits
)? # makes the decimal portion optional
$ # match end of string
To use this in Java you'd want something like:
ets = ","; // commas don't need to be escaped
eds = "\\."; // matches literal dot
regex = "^[+-]?[0-9]{1,3}(" + ets + "[0-9]{3})*(" + eds + "[0-9]+)?$"
Upvotes: 7
Reputation: 89
If I understand correctly, 12. matches because you are matching 0 or 1 occurences of (a period, then 0 or more ocurrences of any number between 0 and 9). So you may have a period and nothing in front of it.
1,,2 matches because you are matching 0 or more occurences of any characters between 0 and 9, or a comma. therefor you could have 0,,,,,,,,,,,,,,0.
If you want the last one not to match, make sure you can only have up to 3 numbers before a comma (in the thousand separator) using curly braces to indicate the amount of ocurrences allowed (i. e. {0,3}) after a set of numbers.
[0-9]{0,3},
@NullUserException just gave a complete regexp that works for your intentions
Upvotes: 1