正则表达式将从任意货币格式中提取美分值 [英] Regex to extract cents value from arbitrary currency formatting
问题描述
我需要使用Java正则表达式从下一个可能的值中提取美分值(千位分隔符既可以是点又可以是逗号):
I need to extract cents value from next possible values using Java regex (thousand separator could be both dot and comma):
$123,456.78
123,456.78 dollars
123,456.78
我有部分可行的解决方案:
I have partially working solution:
[\.,]\d\d\D
我的解决方案的问题是,当最后一位数字是字符串的末尾时,在"123,456.78"的情况下它不起作用.我该如何处理?
The problem with my solution, that it doesn't work in case "123,456.78" when the last digit is the end of string. How can I handle this case?
http://java-regex-tester .appspot.com/regex/6af08221-63cb-4c5b-a865-c86fe5e825ff
推荐答案
请注意,\D
要求一个字符,该字符不是,
/.
之后的数字和您模式中的2位数字.如果要确保没有消耗(要求)就没有数字,请使用负数前瞻:
Note that \D
requires a character that is not a digit after the ,
/.
and 2 digits in your pattern. If you want to make sure there is no digit without consuming (requiring it) use a negative lookahead:
[.,](\d{2})(?!\d)
^^^^^^
请参见 regex演示.
详细信息:
-
[.,]
-点或逗号(以支持不同国家(而不仅仅是美国)的小数点分隔符) -
(\d{2})
-组1(由于\d{2}
出现在捕获组(...)
内,因此您可以使用Matcher.group(1)
访问其值) -
(?!\d)
-否定的前瞻,要求在前2位数字后紧接着没有数字.
[.,]
- a dot or comma (to support decimal separators in different countries, not just the U.S.)(\d{2})
- Group 1 (since the\d{2}
appears inside a capturing group(...)
, you may access its value usingMatcher.group(1)
)(?!\d)
- a negative lookahead requiring the absence of a digit right after the previous 2 digits.
详细了解否定前瞻的工作原理.
这篇关于正则表达式将从任意货币格式中提取美分值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!