Java正则表达式匹配美元金额 [英] Java Regular Expression to match dollar amounts

查看:393
本文介绍了Java正则表达式匹配美元金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我一直在使用

\$?[0-9]+\.*[0-9]*

但当我做一些测试时,我注意到像

But when i was doing some testing i noticed that things like

$$$34.00 

将作为匹配返回(但 matcher.group())只返回匹配的子字符串。如果用户输入一个以上的美元符号,我不希望它甚至传递正则表达式,所以我尝试了这个:

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]*

但这似乎与我第一次输入的正则表达式相同。现在我正在java中测试它,但是,我计划在c ++中使用Boost库来使用它。但请不要在这里给我解决方案,因为我试图在没有人给我答案的情况下学习。

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.

但我确实需要帮助,因此用户只能输入一个美元符号(这就是我所想的 \ $ {1} 会这样做)

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))(\。\\\)?$

细分:

^ \ $ 以$美元符号开头的字符串

^\$ start of string with $ a single dollar sign

([1-9] \d {0,2}(,\d {3})*) 1-3第一个数字不是0的数字,后跟0个或更多个带3个数字的逗号

([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

(([1-9] \d *)?\ d)一个或多个数字,只有当它是唯一的数字时,第一个数字才能为0

(([1-9]\d*)?\d) 1 or more digits where the first digit can be 0 only if it's the only digit

(\.\\\)?$ 周期和2位数字可选字符串结束

(\.\d\d)?$ with a period and 2 digits optionally at the end of the string

匹配:

$4,098.09
$4098.09
$0.35
$0
$380

不匹配:

$098.09
$0.9
$10,98.09
$10,980456

这篇关于Java正则表达式匹配美元金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆