Skip to content
Advertisement

Regular expression in Java for parsing money

I’m looking for are regex for parsing money amounts. The String s10 should not match. Can someone help, or can someone simplify the regex? That’s my try:

JavaScript

Advertisement

Answer

I think you may use

JavaScript

See the regex demo

Details

  • (?<![d,.]) – no digit, . or , allowed immediately on the left
  • (?:d{1,3}(?:(?=([.,]))(?:1d{3})*)?|d+)
    • d{1,3}(?:(?=([.,]))(?:1d{3})*)? – one, two or three digits followed with an optional occurrence of a position followed with a comma or dot followed with 0 or more occurrences of the captured value and then any three digits
    • |d+ – or 1 or more digits
  • (?:(?!1)[.,]d{1,2})? – an optional sequence of a comma or dot, but not the same char as in Group 1, and then 1 or 2 digits
  • (?![,.d]) – no digit, . or , allowed immediately on the right

In Java, do not forget to double the backslashes:

JavaScript
Advertisement