java - 您能否修复此 Java 正则表达式以匹配货币,例如 -10 USD、12.35 AUD ...(Java)?

标签 java regex

我需要验证货币字符串,如下所示:

 1. The Currency Unit must be in Uppercase and must contain 3 characters from A to Z
 2. The number can contain negative (-) or positive (+) sign.
 3. The number can contain the decimal fraction, but if the number contain 
the decimal fraction then the fraction must be 2 Decimal only.
 4. There is no space in the number part

So see this example:

10 USD ------> match
+10 USD ------> match
-10 USD ------> match
10.23 AUD ------> match
-12.11 FRC ------> match
- 11.11 USD ------> NOT match because there is space between negative sign and the number
10  AUD ------> NOT match because there is 2 spaces between the number and currency unit
135.1 AUD ------> NOT match because there is only 1 Decimal in the fraction
126.33 YE ------> NOT match because the currency unit must contain 3 Uppercase characters 

So here is what I tried but failed

if(text != null && text.matches("^[+-]\\d+[\\.\\d{2}] [A-Z]{3}$")){     
  return true;
}

"^\\d+ [A-Z]{3}$" 仅匹配不带任何符号和小数部分的数字。

那么您能否修复此 Java 正则表达式以匹配满足上述要求的货币?

网上的一些其他问题不符合我的要求。

最佳答案

看来您不了解 ? 量词,这意味着该量词描述的元素可以出现零次或一次,使其成为可选。

也就是说,字符串可以在开头包含可选的 -+,只需添加 [-+]?
要说它可以包含 .XX 形式的可选小数部分,其中 X 是数字,只需添加 (\\.\\d{2})?

所以尝试使用 "^[-+]?\\d+(\\.\\d{2})? [A-Z]{3}$"

<小时/>

顺便说一句,如果您使用yourString.matches(regex),那么您不必向正则表达式添加^$。仅当整个字符串与正则表达式匹配时,此方法才会匹配,因此不需要这些元字符。

BTW2 通常你应该在字符类 [...] 中转义 - 因为它代表像 [A-Z] 这样的字符范围,但在这种情况 - 不能以这种方式使用,因为它位于字符类的开头,因此没有“第一个”范围字符,因此您不必转义 - 这里。如果 -[..-] 中的最后一个字符,情况也是如此。这里它也不能表示范围,所以它是简单的文字。

关于java - 您能否修复此 Java 正则表达式以匹配货币,例如 -10 USD、12.35 AUD ...(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21806381/

相关文章:

java - 快速矿工101

regex - 如何在kibana发现中搜索以g,b或a开头的任何城市?

java - 为什么正则表达式中的 "|"(或)用作替换条件时会给出奇怪的结果

regex - 如果字符串包含子字符串,为什么我的条件不满足?

php - 正则表达式查找html div类内容和数据属性? (preg_match_all)

javascript - 获取特定模式内所有单词的正则表达式 (% %)

java - 具有任意 AND 子句的动态 spring 数据 jpa 存储库查询

java - 连接两个数字

java - 构造函数中的自引用算作 "escaping"吗?

java - Soap:使用 WSDL2Java 设置超时