What's a C# regular expression that'll validate currency, float or integer?

孤者浪人 提交于 2019-12-28 06:33:00

问题


What is a regular expression suitable for C# that'll validate a number if it matches the following?

 $1,000,000.150
 $10000000.199
 $10000 
 1,000,000.150
 100000.123
 10000

Or the negative equivalents?


回答1:


You can use csmba's regex if you make one slight modification to it.

^\$?(\d{1,3},?(\d{3},?)*\d{3}(.\d{0,3})?|\d{1,3}(.\d{2})?)$



回答2:


I think ssg is right. It's not a really good use of Regex, especially if your software has to deal with non-US centric data entry.

For instance, if the currency symbol is the Euro, or the Japanese Yen or the British Pound any of the other dozen currency symbols out there?

What about number formatting rules?

In the US you would enter 1,000,000.00 but in France, this should be 1.000.000,00. Other countries allow spacing between digit-grouping...

If you use a straight Regex without taking the Culture into account, then you're never going to validate successfully unless you're 100% sure your software will never ever be used in a non-US centric context.




回答3:


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



回答4:


I think I've found a problem with ssg's solution (or perhaps an MS bug!).

Running this:

float.TryParse("0,2",NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"), out num)

Returns true. Surely "0,2" isn't a valid currency value?




回答5:


Be careful with floats. Eventually you will hit a case such as 0.01 represented as 0.00999999. Strings or integers are better to use.




回答6:


Try this one. It may need some fine tuning to only allow for a single decimal point, but it does match your test cases. I hope this helps.

[$\d,.]+



回答7:


Use this regular expression for US currency \$(\d)*\d Matches $300,$12900 Non-Match $12900.00




回答8:


This regular Expression works for me:

'^[$]{0,1}([0-9]+[,]?[0-9]+|[0-9]{1,3}([.][0-9]{3})*([,][0-9]+)?)$'

with switch

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

it works for

  • $1,000,000.150
  • 10000000.199
  • $10000
  • 1,000,000.150
  • 100000.123
  • 10000


来源:https://stackoverflow.com/questions/617826/whats-a-c-sharp-regular-expression-thatll-validate-currency-float-or-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!