Regex for Currency Amount with D for negative amounts or C for positive amounts

Viewed 216

I need help with RegEx.

Valid values:

-1.00 D
-2,000.00 D
-100,000.56 D
-100,000.00 D
-1,123,456.43 D

1.00 C
2,000.00 C
100,000.56 C
100,000.00 C
1,123,456.43 C

Before Decimal (Whole Numbers) can be upto 13 digits. Decimal should be always 2 digits.

-ve values will have SPACE and then D

and

+ve values will have SPACE and then C

Please help.

2 Answers

Use a look ahead to assert the overall format:

^(?=-.{,21}D|\d.{,20}C)-?\d{1,3}(,\d{3})*\.\d\d [CD]$

See live demo.

You can use the following regular expression to verify that strings match the pattern.

^(?=-.*D$|\d.*C$)-?(?=(?:\d,?){1,13}\.)(?:0|[1-9]\d{0,2}(?:,\d{3})*)\.\d{2} [DC]$

Demo

I tested this with the PCRE regex engine but it should work with any engine the supports lookaheads.

The regex contains two positive lookaheads. The first asserts that the string begins with a hyphen or digit; if a hyphen the last character must be D, if a digit the last character must be C. The second lookahead asserts that the string contains 1-13 digits before the decimal point.

The regex engine performs the following operations.

^                match beginning of line

(?=              begin positive lookahead
  -.*D$          match '-', 0+ chars, 'D' at end of line
  |              or
  \d.*C$         match 1 digit, 0+ chars, 'C' at end of line
)                end positive lookahead

-?               optionally match '-'

(?=              begin positive lookahead
  (?:\d,?)       match 1 digit optionally followed by ','
                 in a non-capture group
  {1,13}         execute preceding non-capture group 1-13 times
  \.             match '.'
)                end positive lookahead

(?:              begin non-capture group
  0              match '0' for amounts < '1.00'
  |              or
  [1-9]\d{0,2}   optionally match '-', then match one digit
                 other than '0', then 0-2 digits   
  (?:,\d{3})     match ',' then 3 digits in non-capture group
  *              execute preceding non-capture group 0+ times
)                end non-capture group
\.\d{2} [DC]     match '.', 2 digits, 1 space 'D' or 'C'
$                match end of string

The end-of-line anchors in the first lookahead are actually not necessary (because of the end-of-line anchor at the end of the regex), but I've included them to improve readability.

Related