Search code examples
regexangularcurrency

Currency regex in Angular


I need Help for currency regex in Angular. I'm not really good at regex.

What I want is a regex that:

  1. allows comma as digital-group-separator, but not in the beginning or the end.
  2. allows only 2 digits rounded after decimal point.
  3. allows only one decimal point and not in the beginning or the end.
  4. not allows 0.00 or 0.

This is my regex:

(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$

but this regex allows 0.00

any one here please help thanks

Desired Outputs

Valid:

1,000.00

1000

0.01

24

1,234,000

11,222,245.22

Not Valid:

,000.00

,,,,,9

0

0.00

1,22,2,

1,000.

123,123,22

000,300.00

000300.00

000,123

000,000

00,000

0,000


Solution

  • You may use

    /^(?![0,.]+$)(?:0|[1-9]\d{0,2}(?:,\d{3})*|[1-9]\d*)(?:\.\d{1,2})?$/
    

    See the regex demo

    Details

    • ^ - start of string
    • (?![0.,]+$) - a negative lookahead that fails the match if there are one or more 0, , or . chars till end of string
    • (?:0|[1-9]\d{0,2}(?:,\d{3})*|[1-9]\d* - either of the three alternatives:
      • 0 - zero
      • | or
      • [1-9]\d{0,2}(?:,\d{3})* - one to three digits with the first one being non-zero, and then 0 or more repetitions of a comma and then three digits
      • | - or
      • [1-9]\d* - 1+ digits with the first one being non-zero,
    • (?:\.\d{1,2})? - an optional sequence of a . and then 1 or 2 digits
    • $ - end of string.