Reputation: 43
Hi I am working on RegEx. Correct response should NOT allow for number to the tenths only, as in RESPONSE = "925.0", nor should it allow for trailing zeros after the hundredths place as in RESPONSE = "925.000". Only correct responses: 925, 0925, 0925., 925., 925.00, 00925
I worked on it and finally came up with this
"^-?(0)*(\d*(\.(00))?\d+.|(\d){1,3}(,(\d){3})*(\.(00))?)$"
It works for three digit numbers but if i want it for 38400.00 it doesn't allow it
Upvotes: 1
Views: 224
Reputation: 12485
I am not quite certain whether the decimal places can be any digit or if they have to be zero. If the former, then this should do the trick:
^-?\d{1,3}(,?\d{3})*(\.(\d{2})?)?$
If the latter, then this:
^-?\d{1,3}(,?\d{3})*(\.(00)?)?$
The entire match starting with the decimal point is optional, and the two decimal places in that match are optional as well.
UPDATE I just realized that it appears you need to accept commas in the response as well - I assume for thousands, millions, etc.
UPDATE #2 per OP's comment
^-?(\d+|\d{1,3}(,\d{3})*)(\.(00)?)?$
UPDATE #3 Added link to regex101 for explanation of this regular expression.
Upvotes: 1
Reputation: 701
Couldn't you do this without the ?'s
^[0-9,]+(\.){0,1}(\d{2}){0,1}$
improved: ^\d+[0-9,]*(\.){0,1}(\d{2}){0,1}$
Edit: Broken down a bit as requested
Old one:
[0-9,]+
1 or more digits/commas (would have accepted ',' as true) so improved version:
\d+
for starts with 1 or more digits
[0-9,]*
0 or more digits/commas
followed by
(\.){0,1}
0 or 1 decimal
Followed by
(\d{2}){0,1}
0 or 1 of (exactly 2 digits)
Upvotes: 0
Reputation:
I think your problem is that you're trying to match it in chunks of three, with commas separating, but 38400.00
doesn't have commas.
Try this:
^-?\d+(\.?(\d{2})?)$
The -
indicates the character, -. With the ?
after, it says that it may or may not apply. This allows negative numbers, so if you only want positive numbers matched, delete the first two characters.
\d
represents every digit. The +
after says that there can be as many as you want, as long as there's at least one.
Then there's a \.
, which is just a dot in the number. The ?
does the same as before.. Since you seem to allow trailing periods, I assumed you wanted it to be considered separately from the following digits.
The ()
encloses the next group, which is the period (\.
) followed by two characters that match \d
-- two digits -- and which may be repeated 0 or 1 times, as dictated by the ?
. This allows people to either have no digits after the period or two, but nothing else.
The ^
at the beginning specifies it has to be at the beginning of the line, and the $
at the end specifies it has to end at the end of the line. Remember to enable the multiline (m
) flag so it works properly.
Disclaimer: I've not done much regex work before, so I could well be totally off. If it doesn't work, let me know.
Upvotes: 0