2009-08-31 71 views
2

我需要在AS3中编写一个RegExp,它将Excel格式的货币值解析为一个数字: E.g. 正则表达式($ 35,600.00)= 35600RegExp解析货币值

并检查它是否格式正确(以“,”作为千位分隔符,“。”作为小数点。货币符号可以是任意的(不只是$)和可以忍受的开头或结尾。

所以我只需要从数量剥去每一个非数字,检查是否是有效的。

谢谢! 马丁

回答

6

你需要2箱子,一个用逗号分隔,另一个用十进制分隔整数

如果是整数,请将逗号或小数点后的所有内容(取决于您的格式)删除。然后运行下面的正则表达式:

这将删除所有的非数字字符:

s/\D+//g; 

如果你没有一个整数,你将需要包括整个数字分隔异常:

小数分隔:

s/[^\d.]+//g 

逗号分隔符:

s/[^\d,]+//g 

*免责声明:我只是在我的脑海中解析这些正则表达式,所以我的语法可能会稍微偏离。

+0

这也将照顾,如果我有逗号作为千位分隔符和小数点分隔符? 不知何故,AS3不喜欢这种正则表达式格式 – Martin 2009-08-31 15:29:23

+0

Martin,没有AS3正则表达式格式的使用经验,但如果你放弃像s /和g +这样的边缘,那么就拿这个匹配的结果。 – 2009-08-31 15:32:34

+1

@Chris Ballance:是的,你的正则表达式语法是关闭的;检查我的编辑。 – 2009-09-01 07:19:50

0
[$|£|<insert more pipe sepatared options here>]?(\d)*(,)?(\d)*.\d\d[$|£|<insert more pipe sepatared options here>]? 

可能工作。

1

剥离前导和尾随货币符号和空格后,可以使用以下表达式。

 
[1-9][0-9]{1,2}(,[0-9]{3})*(.[0-9]{2})+ 

也就是说

 
(
    [1-9][0-9]{0,2} One to three digits, no leading zero, followed by 
    (,[0-9]{3})*  a thousands separator and three digits, zero or more times, 
    |     or 
    0    a leading zero. 
) 
(.[0-9]{2})?   Optional a decimal point followed by exactly two digits. 

处理货币符号好听点是不是最容易的事情,因为你必须避免与领先和后货币符号输入。解决方案将使用前瞻断言。

 
(?=$(([$€] ?)?[0-9,.]+|[0-9,.]+(?[$€]))^)[$€ ]+<ExpressionFromAbove>[$€ ]+ 

这样做如下。

 
(?=     Positive look ahead assertion. 
    $     Anchor start of line. 
    (     Begin options. 
    ([$€] ?)?   Optional leading currency symbol followed by an optional space 
    [0-9,.]+   and one or more digits, thousand separators, and decimal points 
    |     or 
    [0-9,.]+   one or more digits, thousand separators, and decimal points 
    (?[$€])   followed by an optional space and and a currency symbol. 
)     End options. 
^     Anchor end of line. 
) 
[$€ ]+    Leading currency symbol and optional space. 
<ExpressionFromAbove> Match the actual number. 
[$€ ]+    Trailing optional space and currency symbol. 

如果你知道,该格式是正确的,去掉一切,是不是数字或小数点,它解析为一个小数(这将被使用在C#Decimal.Parse()),或,如果没有合适的解析方法,只需在小数点处拆分,解析为整数,然后合并两个数字。