Sami
Sami

Reputation: 127

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

Upvotes: 2

Views: 2877

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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

Upvotes: 2

Yonah Karp
Yonah Karp

Reputation: 671

This should do the trick

\d{1,3}(?:.|,)+€?

and for java it should be "\\d{1,3}(?:.|,)+€?"

I highly recommend http://regexr.com for all your regex needs. They have a great "cheatsheet" and a nice testing environment

Upvotes: 0

Related Questions