HQT

追求.NET 技术永无止境

导航

判断一字符串是否为数字的正则表达式

Posted on 2005-09-02 14:34  HQT  阅读(2260)  评论(0编辑  收藏  举报

public class Common
{
public static bool IsNumber(string s,int precision,int scale)
  {
   if((precision == 0)&&(scale == 0))
   {
    return false;
   }
   string pattern = @"(^\d{1,"+precision+"}";
   if(scale>0)
   {
    pattern += @"\.\d{0,"+scale+"}$)|"+pattern;
   }
   pattern += "$)";
   return Regex.IsMatch(s,pattern);
  }
}

用 Nunit 进行单元测试:

  [Test] public void TestNumber()
  {
   Assert.IsFalse(!Common.IsNumber("1.0")); 
   Assert.IsFalse(Common.IsNumber("A")); 
   Assert.IsFalse(Common.IsNumber("1.")); 
   Assert.IsFalse(Common.IsNumber("123456789",5,0)); 
   Assert.IsFalse(Common.IsNumber("1234567891",9,2)); 
   Assert.IsFalse(!Common.IsNumber("123456789.0",9,2)); 
   Assert.IsFalse(Common.IsNumber("123456789.123",9,2)); 
  }

都能通过.