正则表达式表示货币金额,D 表示负金额,C 表示正金额



我需要正则表达式的帮助。

有效值:

-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

十进制之前(整数(最多可以包含 13 位数字。小数应始终为 2 位数字。

-ve 值将具有空格,然后具有 D

+ve 值将具有空格,然后是 C

请帮忙。

使用展望来断言整体格式:

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

观看现场演示。

可以使用以下正则表达式来验证字符串是否与模式匹配。

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

演示

我用 PCRE 正则表达式引擎对此进行了测试,但它应该适用于任何支持前瞻的引擎。

正则表达式包含两个积极的展望。第一个断言字符串以连字符或数字开头;如果是连字符,则必须D最后一个字符,如果是数字,则必须C最后一个字符。第二个前瞻断言字符串在小数点前包含 1-13 位数字。

正则表达式引擎执行以下操作。

^                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

第一次查看中的行尾锚点实际上不是必需的(因为正则表达式末尾的行尾锚点(,但我已包含它们以提高可读性。