C#判断一个String是否为数字类型
方案一:Try...Catch(执行效率不高)
privateboolIsNumberic(stringoText) { try { intvar1=Convert.ToInt32(oText); returntrue; } catch { returnfalse; } }
方案二:正则表达式(推荐)
a)
publicstaticboolIsNumeric(stringvalue) { returnRegex.IsMatch(value,@"^[+-]?/d*[.]?/d*$"); } publicstaticboolIsInt(stringvalue) { returnRegex.IsMatch(value,@"^[+-]?/d*$"); } publicstaticboolIsUnsign(stringvalue) { returnRegex.IsMatch(value,@"^/d*[.]?/d*$"); }
b)
usingSystem; usingSystem.Text.RegularExpressions;
publicboolIsNumber(StringstrNumber) { RegexobjNotNumberPattern=newRegex("[^0-9.-]"); RegexobjTwoDotPattern=newRegex("[0-9]*[.][0-9]*[.][0-9]*"); RegexobjTwoMinusPattern=newRegex("[0-9]*[-][0-9]*[-][0-9]*"); StringstrValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"; StringstrValidIntegerPattern="^([-]|[0-9])[0-9]*$"; RegexobjNumberPattern=newRegex("("+strValidRealPattern+")|("+strValidIntegerPattern+")");
return!objNotNumberPattern.IsMatch(strNumber)&& !objTwoDotPattern.IsMatch(strNumber)&& !objTwoMinusPattern.IsMatch(strNumber)&& objNumberPattern.IsMatch(strNumber); }