简体   繁体   English

验证C#中的货币格式

[英]Validate currency format in C#

I would like to validate whether a string satisfy the following currency format with maximum 4 decimal places and could allow comma , regardless of culture and the comma could be at places of standard practice . 我想验证一个字符串是否满足以下货币格式(最多4个小数位)并且可以允许逗号, 无论其区域性如何),并且逗号可以放在标准习惯的位置

Eg: 例如:

2,000,000(valid)  
200000.0000(valid)  
200 (valid)  
200.00000(invalid)

How could it be done? 怎么做?

You can do Regex match for your purpose. 您可以根据需要进行正则Regex匹配。

The Regex below works for your specific examples. 下面的正则Regex适用于您的特定示例。 But, it'll accept comma , at random places. 但是,它会接受逗号,在随机的地方。 Demo here. 演示在这里。

^\d+(\,\d+)*(\.\d{1,4})?$

A better Regex would be the following. 更好的正则Regex如下。 Check the demo . 检查演示 Base Regex taken from this post. 基地正则表达式取自这个职位。

^\$?(\d{1,3},(\d{3},)*\d{3}|\d+)(.\d{1,4})?$

Update 更新资料

To answer comment - above Regex allows 0090 . 要回答以上评论,正则Regex允许0090 Try this one. 试试这个。 Demo here . 演示在这里

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

Update 2 更新2

C# usage C#用法

var currencyString = "1,234,456.7890";
var regex = @"^((([1-9]\d{0,2},(\d{3},)*\d{3}|[1-9]\d*)(.\d{1,4})?)|(0\.\d{1,4}))$";
var isValidCurency = Regex.IsMatch(currencyString, regex);

Update 3 更新3

As per OP, comma , is allowed at any place. 按照OP,逗号,在任何地方允许的。 Updated Regex with demo here . 在此处通过演示更新了Regex

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

Update 4 更新4

Use this one. 使用这个。 Demo HERE . 演示这里

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

Well, this :) 好吧, :)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM