Home > Software design >  Regular Expression for negative accounting money values?
Regular Expression for negative accounting money values?

Time:11-13

I am having a hard time finding a solution for negative accounting/money values that look like:

(1.00)

(100)

(100.00)

I've tried this, but for some reason, it's allowing values such as 'abcd'.

^0\.00||(\(\d*(?:\.\d{1,2})?\))?$

CodePudding user response:

It does not match abcd, but if you test if the string has a match, then it will be true as there are positions that match.

As all the digits are optional at the end of the string, there is a position that can match.

Also the || matches a position after 0.00, before and after the digits part and on every position in abcd or an empty string.


You can change the || to |, match at least a single digit and use the alternation for both alternatives:

^(?:0\.00|\(\d (?:\.\d{1,2})?\))$
  • ^ Start of string
  • (?: Non capture group for the alternation
    • 0\.00 Match 0.00
    • | Or
    • \(\d (?:\.\d{1,2})?\) Match ( 1 digits, optionally . and 1-2 digits and )
  • ) Close non capture group
  • $ End of string

Regex demo

  • Related