java 金额正则表达式,Java正则表达式匹配美元金额

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值