正则表达式验证数字到小数点后两位

时间:2018-07-18 12:09:33

标签: c# regex

我需要一些 regex ,它们将匹配仅十进制的数字两个位置。例如

   123 : Match
12.123 : No match
 12.34 : Match

2 个答案:

答案 0 :(得分:2)

也许您不需要正则表达式,以它为例。

class Program
{
    static void Main(string[] args)
    {
        string[] tests = new string[] {
            "123",               // false
            "12.123",            // false
            "12.34",             // true
            "12.3",              // false
            "abc.de",            // false
            "123,456.23"         // true
        };

        foreach (var test in tests)
        {
            Console.WriteLine(ValidateDecimals(test)); 
        }

    }

    public static bool ValidateDecimals(string input)
    {
        if(!decimal.TryParse(input, NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint, null, out _)) return false;

        var parts = input.Split('.');
        return parts.Length == 2 && parts[1].Length == 2;
    }
}

答案 1 :(得分:2)

如果您的意思是最多 2个小数点,则可以尝试

^\-?[0-9]+(?:\.[0-9]{1,2})?$

模式

string[] tests = new string[] {
   "123",
   "12.123",
   "12.34",
   "12.3",
 };

string pattern = @"^\-?[0-9]+(?:\.[0-9]{1,2})?$";

var report = string.Join(Environment.NewLine, tests
  .Select(test => $"{test,7} : {(Regex.IsMatch(test, pattern) ? "Match" : "No match")}"));

Console.Write(report);

结果:

    123 : Match
 12.123 : No match
  12.34 : Match
   12.3 : Match

如果您完全不表示小数部分,或者精确地 2位数字:

^\-?[0-9]+(?:\.[0-9]{2})?$

结果:

    123 : Match
 12.123 : No match
  12.34 : Match
   12.3 : No match
相关问题