C# 判断字符串是否为数字
public class NumberUtils {
public static bool IsNumber(string strNumber) {
Regex objTwoDotPattern = new Regex(@"[0-9]+[.][0-9]+[.][0-9]+");
Regex objTwoMinusPattern = new Regex(@"[0-9]+[-][0-9]+[-][0-9]+");
string strValidRealPattern = @"^[+-]?\d*[.]?\d+$";
string strValidIntegerPattern = @"^[+-]?\d+$";
Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
return !objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
}
public static bool IsInt(string value) {
return Regex.IsMatch(value, @"^[+-]?\d+$");
}
public static bool IsNumberic(string value) {
return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d+$");
}
}
测试:
[TestClass()]
public class NumberUtilsTests {
[TestMethod()]
public void IsNumberTest() {
string s = "1";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "12";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "123";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "1234";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "12345";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "123456";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "1234567";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "-";
Assert.IsFalse(NumberUtils.IsNumber(s));
s = "+";
Assert.IsFalse(NumberUtils.IsNumber(s));
s = "-0";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "-1";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "-100";
Assert.IsTrue(NumberUtils.IsNumber(s));
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "-.12";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "+.12";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "-12.12";
Assert.IsTrue(NumberUtils.IsNumber(s));
s = "+12.12";
Assert.IsTrue(NumberUtils.IsNumber(s));
}
[TestMethod()]
public void IsIntTest() {
string s = "1";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "12";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "123";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "1234";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "12345";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "123456";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "1234567";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "-";
Assert.IsFalse(NumberUtils.IsInt(s));
s = "+";
Assert.IsFalse(NumberUtils.IsInt(s));
s = "-0";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "-1";
Assert.IsTrue(NumberUtils.IsInt(s));
s = "-100";
Assert.IsTrue(NumberUtils.IsInt(s));
}
[TestMethod()]
public void IsNumbericTest() {
string s = "1";
Assert.IsTrue(NumberUtils.IsNumberic(s));
s = "12";
Assert.IsTrue(NumberUtils.IsNumberic(s));
s = "-.12";
Assert.IsTrue(NumberUtils.IsNumberic(s));
s = "+.12";
Assert.IsTrue(NumberUtils.IsNumberic(s));
s = "-12.12";
Assert.IsTrue(NumberUtils.IsNumberic(s));
s = "+12.12";
Assert.IsTrue(NumberUtils.IsNumberic(s));
}
}