如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
下面是c#方法。 Int。TryParse方法(String, Int32)
其他回答
int n;
bool isNumeric = int.TryParse("123", out n);
从c# 7开始更新:
var isNumeric = int.TryParse("123", out int n);
或者,如果不需要这个数字,可以丢弃out参数
var isNumeric = int.TryParse("123", out _);
变量可以被它们各自的类型替换!
如果输入的都是数字,则返回true。不知道它是否比TryParse更好,但它会工作。
Regex.IsMatch(input, @"^\d+$")
如果您只想知道它是否有一个或多个数字与字符混合,请省略^ +和$。
Regex.IsMatch(input, @"\d")
编辑: 实际上,我认为它比TryParse更好,因为一个很长的字符串可能会溢出TryParse。
在项目中导入Visual Basic引用并使用其信息。IsNumeric方法,如下所示,并且能够捕获浮点数以及整数,不像上面的答案只捕获int。
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
如果你想捕获更广泛的数字,à la PHP的is_numeric,你可以使用以下方法:
// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)
// Finds whether the given variable is numeric.
// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.
// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
new Regex( "^(" +
/*Hex*/ @"0x[0-9a-f]+" + "|" +
/*Bin*/ @"0b[01]+" + "|" +
/*Oct*/ @"0[0-7]*" + "|" +
/*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" +
")$" );
static bool IsNumeric( string value )
{
return _isNumericRegex.IsMatch( value );
}
单元测试:
static void IsNumericTest()
{
string[] l_unitTests = new string[] {
"123", /* TRUE */
"abc", /* FALSE */
"12.3", /* TRUE */
"+12.3", /* TRUE */
"-12.3", /* TRUE */
"1.23e2", /* TRUE */
"-1e23", /* TRUE */
"1.2ef", /* FALSE */
"0x0", /* TRUE */
"0xfff", /* TRUE */
"0xf1f", /* TRUE */
"0xf1g", /* FALSE */
"0123", /* TRUE */
"0999", /* FALSE (not octal) */
"+0999", /* TRUE (forced decimal) */
"0b0101", /* TRUE */
"0b0102" /* FALSE */
};
foreach ( string l_unitTest in l_unitTests )
Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );
Console.ReadKey( true );
}
请记住,仅仅因为值是数字类型并不意味着它可以转换为数字类型。例如,“999999999999999999999999999999999999999999999999”是一个完全有效的数值,但它不适合. net数值类型(也就是说,不是标准库中定义的数值类型)。
在c# 7中,你可以内联out变量:
if(int.TryParse(str, out int v))
{
}