Regex to extract cents value from arbitrary currency formatting

强颜欢笑 提交于 2019-12-11 01:12:50

问题


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

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


回答1:


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)
           ^^^^^^ 

See the regex demo.

Details:

  • [.,] - 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 using Matcher.group(1))
  • (?!\d) - a negative lookahead requiring the absence of a digit right after the previous 2 digits.

See more about how negative lookahead works.



来源:https://stackoverflow.com/questions/40628738/regex-to-extract-cents-value-from-arbitrary-currency-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!