Price Field Regular Expression Without Prefixed 0 for Cents
I'm using the following regular expression to validate a price field:
(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2开发者_JAVA百科})?$
It works absolutely perfectly except for when a user types in a price of the form .60, etc. If I add a 0 in front, like 0.60, it seems to work fine, but I would like to allow the user to ommit the 0 as a prefix.
Use this syntax for (optional_subgroup)? i.e. nest in another pair of parentheses '(...)' and append '?'
In your case, the entire integer subpart (\d{1,3}(\,\d{3})*|(\d+))
is optional. Hence
((\d{1,3}(\,\d{3})*)|(\d+))?(\.\d{2})?$
However now this will match totally empty expressions, i.e. 0 integer and 0 decimal digits. So we must require either at least 1 integer digit (+ optional decimal part)...
((\d{1,3}(\,\d{3})*)|(\d+))(\.\d{2})?
or at least 2 decimal digits (+ optional integer part))...
((\d{1,3}(\,\d{3})*)?|(\d+))(\.\d{2})
So match either of those two (INTEGER)(DECIMAL)?|(INTEGER)?(DECIMAL)
- we could compress your regex if you tell us more.
Alternatively, postprocess the match (in ASP) to reject the 0 integer + 0 decimal digits case. (Can you post that ASP snippet?)
Don't match a decimal point all by itself. It's up to you whether you allow a single decimal digit: .1
(\d{1,3}(\,\d{3})*|(\d*))(\.\d{2})?$
精彩评论