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

前端 未结 8 2341
闹比i
闹比i 2020-12-06 12:21

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,         


        
相关标签:
8条回答
  • 2020-12-06 13:02
    ^\$?(\d{1,3},?(\d{3},?)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{2})?)$
    
    0 讨论(0)
  • 2020-12-06 13:03

    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?

    0 讨论(0)
  • 2020-12-06 13:13

    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
    0 讨论(0)
  • 2020-12-06 13:14

    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.

    0 讨论(0)
  • 2020-12-06 13:16

    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})?)$
    
    0 讨论(0)
  • 2020-12-06 13:16

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

    0 讨论(0)
提交回复
热议问题