我需要验证货币字符串,如下所示:
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/