使用正则表达式匹配货币金额,D表示负数金额,C表示正数金额。

3

我需要在正则表达式方面寻求帮助。

有效数值:

-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位数字。

负值将带有空格,然后是D。

正值将带有空格,然后是C。

请帮忙。


你使用的正则表达式引擎是哪个?你目前尝试了什么? - on8tom
2个回答

2

使用先行断言来验证整体格式:

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

请查看实时演示


@Cary 确实如此!现在已经全部修复 :) - Bohemian

1
你可以使用以下正则表达式来验证字符串是否符合模式。
^(?=-.*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

第一个先行断言中的行尾锚点实际上并不是必需的(因为正则表达式末尾有行尾锚点),但我包含它们是为了提高可读性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接