This is what i've been using
\$?[0-9]+\.*[0-9]*
But when i was doing some testing i noticed that things like
$$$34.00
would return as a match (but matcher.group()) just returns the matched substring. I don't want it to even pass the regular expression if the user enters more than one dollar sign so i tried this:
\${1}[0-9]+\.*[0-9]*
but this seems to behave the same as the regular expression i first typed. Right now i'm testing this in java but, i plan to use it in c++ using the Boost libraries. But Please don't give me that solution here because i'm trying to learn without someone giving me the answer.
But i do need help making it so the user can only enter one dollar sign (which is what i thought \${1} would do)
解决方案
Since you're doing this to learn regex...
^\$(([1-9]\d{0,2}(,\d{3})*)|(([1-9]\d*)?\d))(\.\d\d)?$
Breakdown:
^\$ start of string with $ a single dollar sign
([1-9]\d{0,2}(,\d{3})*) 1-3 digits where the first digit is not a 0, followed by 0 or more occurrences of a comma with 3 digits
or
(([1-9]\d*)?\d) 1 or more digits where the first digit can be 0 only if it's the only digit
(\.\d\d)?$ with a period and 2 digits optionally at the end of the string
Matches:
$4,098.09
$4098.09
$0.35
$0
$380
Does not match:
$098.09
$0.9
$10,98.09
$10,980456