Search code examples
javaregexcurrency

validate number and currency with regex


I'm working on a regex but don't know exactly what to do further. These are my regex:
1) "^-?\\d{1,3}(?:\\.\\d{3})*(?:,\\d+)?\\s$";
2) "^-?\\d{1,3}(?:\\.\\d{3})*(?:,\\d+)?\\s\\€$"
3) "[0-9.,]*"
4) "[0-9.,€]*"

these regex check either for currency String or numbers. Example to each one
1) 123.456,99
2) 123.456,99 €
3) 12,19
4) 12,19 €

Each regex works for the related example. Is there a posibility to combine all those regex to one? and how can i make this regex flexible to whitespaces at any position in that string.

thx in advance

Sami


Solution

  • You can use ^-?(\d{1,3}\s*?([.,]|$|\\s)\\s*?)+€?$

    • ^-?(\\d{1,3}\\s*?([.,]|$|\\s)\\s*?)+€?$ : ^ starts with

      • (\\d{1,3}\s*?([.,]|$|\\s)\\s*?)+ match one or more pair of digits, separated by . or ,
      • \\d{1,3}\\s*? match digits between 1 to 3 , match spaces as less as possible
      • ([.,]|$|\s)\\s*? zero or one match of . or , or end or space , \\s*? zero or more spaces
    • €?$ zero or one match of character , $ end of match

    Java Demo