确定字符串是否为数字

Identify if a string is a number

提问人:Gold 提问时间:5/22/2009 最后编辑:Alexander AbakumovGold 更新时间:5/31/2023 访问量:1484453

问:

如果我有这些字符串:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

是否有命令(例如或其他命令)可以识别字符串是否为有效数字?IsNumeric()

C# 字符串 分析 是数值的

评论

82赞 Lucas 5/22/2009
从他们的例子中,你可以看到他们的意思是整个字符串是否代表一个数字。
58赞 Mohsen 10/23/2013
返回链。全部(Char.IsDigit);
18赞 Harald Coppoolse 10/20/2014
str.All(Char.IsDigit) 将声明“3.14”为假,以及“-2”和“3E14”。更不用说:“0x10”
4赞 Alex Mazzariol 8/22/2015
这取决于您尝试检查的号码类型。对于没有分隔符的整数(即十进制数字字符串),此检查有效,并且与接受的答案和 OP 中隐含的答案相同。
1赞 Novastorm 3/22/2018
@Lucas感谢您的评论,您不知道我尝试将字符串 double 解析为 int 并想知道为什么它失败了......

答:

1513赞 mqp 5/22/2009 #1
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 _);

var s 可以替换为它们各自的类型!

评论

164赞 John Gietzen 5/22/2009
不过,我会使用 double。TryParse,因为我们想知道它是否代表一个数字。
7赞 user2323308 8/28/2013
如果我将字符串作为“-123”或“+123”传递,函数将返回 true。我知道整数有正值和负值。但是,如果此字符串来自用户输入的文本框,则它应该返回 false。
18赞 BlackTigerX 10/24/2014
这是一个很好的解决方案,直到用户输入的值超过 -2,147,483,648 到 2,147,483,647,然后静默失败
5赞 Baloo0ch 1/22/2018
我更喜欢此检查的扩展方法:public static bool IsNumeric(this string text) { double _out; return double.TryParse(text, out _out); }
4赞 Jalali Shakib 3/13/2018
最好使用“长。TryParse“,用于最长的字符串。例如,“2082546844562”是一个数字,但不能解析为整数。
32赞 TheTXI 5/22/2009 #2

您始终可以对许多数据类型使用内置的 TryParse 方法,以查看相关字符串是否会通过。

例。

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

结果将 = True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

结果将 = False

评论

0赞 TheTXI 5/22/2009
我想我可能比 C# 更多地使用 VB 样式语法来做到这一点,但同样的规则也适用。
11赞 Craig 5/22/2009 #3

可以使用 TryParse 来确定是否可以将字符串分析为整数。

int i;
bool bNum = int.TryParse(str, out i);

布尔值会告诉你它是否有效。

11赞 Gabriel Florit 5/22/2009 #4

如果你想知道一个字符串是否是一个数字,你可以随时尝试解析它:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

请注意,返回一个 ,您可以使用它来检查解析是否成功。TryParsebool

8赞 user447688 5/22/2009 #5

Double.TryParse

bool Double.TryParse(string s, out double result)
28赞 BFree 5/22/2009 #6

如果您不想使用 int.解析或加倍。解析,你可以用这样的东西来滚动你自己的:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}

评论

7赞 Lucas 5/22/2009
如果它们只表示整数呢?“.”是组分隔符而不是逗号(例如pt-Br)的区域设置呢?负数呢?组分隔符(英文逗号)?货币符号?TryParse() 可以根据需要使用 NumberStyles 和 IFormatProvider 管理所有这些。
0赞 BFree 5/22/2009
哦,是的,我更喜欢所有版本。我从来没有真正使用过那个扩展方法,好电话。虽然它应该是 s.ToCharArray()。全部(..)。至于你的第二点,我听到了,这就是为什么我以如果你不想使用 int 开头。解析。。。。(我假设这有更多的开销......
11赞 Clément 1/6/2011
不过,1.3.3.8.5 并不是一个真正的数字,而 1.23E5 是。
0赞 ruffin 8/16/2014
@BFree:“虽然它应该是 s.ToCharArray()。All(..)“ -- 意识到我疯狂地迟到了,这不是真的。每个字符串“是”都已经是一个 char 数组。整洁,是吧?虽然该行缺少 ,否则您会收到错误: And @RusselYang - 所有逻辑都是有缺陷的;问题是你不介意运送哪些错误。;^)但我明白你的意思。charMember 'char.IsDigit(char)' cannot be accessed with an instance reference; qualify it with a type name instead.All(c => char.IsDigit(c) || c == '.'))
2赞 Millie Smith 9/13/2014
@Lucas我同意 TryParse 处理更多,但有时这不是必需的。我只需要验证我的信用卡号框(只能有数字)。这个解决方案几乎肯定比 try parse 快。
34赞 Euro Micelli 5/22/2009 #7

这可能是 C# 中的最佳选择。

如果您想知道字符串是否包含整数(整数):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

TryParse 方法将尝试将字符串转换为数字(整数),如果成功,它将返回 true 并将相应的数字放在 myInt 中。如果不能,则返回 false。

使用其他响应中所示的替代方法的解决方案有效,但速度要慢得多,因为抛出异常的代价非常高。 在版本 2 中添加到 C# 语言中,在此之前您别无选择。现在你这样做了:因此你应该避免替代方案。int.Parse(someString)TryParse(...)Parse()

如果要接受十进制数,decimal 类也有一个方法。在上面的讨论中,将 int 替换为 decimal,同样的原则也适用。.TryParse(...)

评论

0赞 jimjim 11/7/2019
为什么 TryParse 比将所有字符与整数字符进行比较更好?
146赞 Nelson Miranda 5/22/2009 #8

我已经多次使用这个函数:

public static bool IsNumeric(object Expression)
{
    double retNum;

    bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
    return isNum;
}

但你也可以使用;

bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false

基准测试 IsNumeric 选项

alt text
(来源:aspalliance.com

alt text
(来源:aspalliance.com

评论

91赞 Lucas 5/22/2009
从 C# 应用引用 Microsoft.VisualBasic.dll?eww :P
12赞 Euro Micelli 5/22/2009
好吧,VB。NET 的 IsNumeric() 内部使用 double。TryParse(),在 VB6 兼容性所需的许多回旋之后(除其他外)。如果您不需要兼容性,请加倍。TryParse() 使用起来同样简单,它通过在进程中加载 Microsoft.VisualBasic.dll 来避免浪费内存。
4赞 Clément 1/6/2011
快速说明:如果您设法一劳永逸地构建底层有限状态机,那么使用正则表达式会快得多。通常,构建状态机需要 O(2^n),其中 n 是正则表达式的长度,而读取是 O(k),其中 k 是被搜索字符串的长度。因此,每次重建正则表达式都会引入偏差。
2赞 Nyerguds 4/4/2016
@Lucas 实际上,里面有一些非常好的东西,比如一个完整的 csv 解析器。如果它存在在那里,没有理由不使用它。
1赞 6/21/2022
这个答案在我看来是最好的,因为考虑到上述事实,这个答案是最快的,这里也提到了 qawithexperts.com/questions/460/......
-1赞 Syed Tayyab Ali 5/22/2009 #9

下面是 C# 方法。Int.TryParse 方法 (String, Int32)

394赞 John M Gant 5/22/2009 #10

如果全部为数字,则返回 true。不知道它是否比 更好,但它会起作用。inputTryParse

Regex.IsMatch(input, @"^\d+$")

如果您只想知道它是否将一个或多个数字与字符混合在一起,请省略 和 .^+$

Regex.IsMatch(input, @"\d")

编辑:实际上,我认为它比 TryParse 更好,因为很长的字符串可能会溢出 TryParse。

评论

2赞 Clément 1/6/2011
不过,一劳永逸地构建正则表达式会更有效率。
23赞 Michal B. 12/18/2012
@MAXE:我不同意。正则表达式检查速度非常慢,因此,如果考虑性能,通常会有更好的解决方案。
8赞 Simon_Weaver 11/23/2013
编辑:如果您正在运行数千个这样的参数,则可以将其添加为参数,以提高速度RegexOptions.CompiledRegex.IsMatch(x.BinNumber, @"^\d+$", RegexOptions.Compiled)
14赞 Noctis 5/16/2014
也会在负面因素和.
5赞 BenKoshy 11/3/2015
对于任何菜鸟,您需要添加:使用 System.Text.RegularExpressions;在 Visual Studio 类的顶部
1赞 Arun 1/2/2013 #11

希望这会有所帮助

string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);

if isNumber 
{
//string is number
}
else
{
//string is not a number
}
15赞 JDB 4/30/2013 #12

如果你想捕捉更广泛的数字,就像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 );
}

请记住,仅仅因为值是数字并不意味着它可以转换为数字类型。例如,是一个有效的数值,但它不适合 .NET 数值类型(即,不是在标准库中定义的类型)。"999999999999999999999999999999.9999999999"

评论

0赞 Steve Hibbert 3/25/2014
在这里不想成为一个聪明的 alec,但对于字符串“0”来说,这似乎失败了。我的正则表达式不存在。有没有简单的调整?我得到“0”,可能还有“0.0”,甚至“-0.0”作为可能的有效数字。
0赞 JDB 3/25/2014
@SteveHibbert - 每个人都知道“0”不是一个数字!说真的......将正则表达式调整为匹配 0。
0赞 Steve Hibbert 3/25/2014
嗯,是我,还是“0”仍然不被识别为数字?
1赞 Steve Hibbert 3/26/2014
由于懒惰且不了解正则表达式,我剪切粘贴了上面的代码,看起来它包含“0.0”类型更改。我运行了一个测试来检查字符串“0”是否正在运行。IsNumeric(),返回 false。我认为八进制测试将对具有两个数字字符的任何内容返回 true,其中第一个是零(第二个是零到七),但对于它本身只有一个大胖孤独的零,它将返回 false。如果你用上面的代码测试“0”,你会得到假吗?抱歉,如果我知道更多的正则表达式,我将能够提供更好的反馈。必须阅读。
1赞 Steve Hibbert 3/26/2014
!哎呀!只需重新阅读您上面的评论,我错过了额外的星号,我只更新了小数行。这样一来,您就是对的,“0”IsNumeric。对于您的烦恼,我们深表歉意,非常感谢您的更新,希望它也能帮助其他人。感谢。
0赞 ΩmegaMan 7/18/2013 #13

在项目中拉取对 Visual Basic 的引用,并使用其 Information.IsNumeric 方法(如下所示),并且能够捕获浮点数和整数,这与上面的答案不同,它只捕获整数。

    // Using Microsoft.VisualBasic;

    var txt = "ABCDEFG";

    if (Information.IsNumeric(txt))
        Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false

评论

0赞 JDB 3/26/2014
这种方法的一个潜在问题是对字符串进行字符分析。因此,像这样的数字将注册为 ,即使没有办法使用标准数字类型来表示这个数字。IsNumeric9999999999999999999999999999999999999999999999999999999999.99999999999True
11赞 Hein Andre Grønnestad 3/7/2014 #14

我想这个答案只会在所有其他答案之间丢失,但无论如何,这里是。

我最终通过谷歌解决了这个问题,因为我想检查是否是,以便我可以使用它而不是方法。stringnumericdouble.Parse("123")TryParse()

为什么?因为在知道解析是否失败之前必须声明变量并检查结果很烦人。我想使用 来检查是否是,然后在第一个三元表达式中解析它或在第二个三元表达式中提供默认值。outTryParse()ternary operatorstringnumerical

喜欢这个:

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

它只是比以下文件干净得多:

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

我为这些情况做了几个扩展方法


扩展方法一

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

例:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

因为尝试将字符串解析为适当的类型,而不仅仅是检查字符串是否为“数字”,所以它应该非常安全。您甚至可以将它用于具有方法的非数值类型,例如 .IsParseableAs()TryParse()DateTime

该方法使用反射,您最终会调用该方法两次,这当然不是那么有效,但并非所有内容都必须完全优化,有时便利性更重要。TryParse()

此方法还可用于轻松地将数字字符串列表解析为具有默认值的列表或其他类型的列表,而无需捕获任何异常:double

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

扩展方法二

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

此扩展方法允许您将具有方法的 any 解析为任何方法,并且还允许您指定在转换失败时返回的默认值。stringtypeTryParse()

这比将三元运算符与上述扩展方法一起使用要好,因为它只执行一次转换。不过,它仍然使用反射......

例子:

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

输出:

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00

评论

4赞 JDB 3/26/2014
我相信你可能已经发明了我见过的最低效的方法之一。您不仅要解析字符串两次(在可解析的情况下),还要多次调用反射函数来执行此操作。而且,最后,您甚至不会使用扩展方法保存任何击键。
2赞 Hein Andre Grønnestad 3/26/2014
谢谢你重复我自己在倒数第二段中写的内容。此外,如果您考虑到我的最后一个示例,您肯定会使用此扩展方法保存击键。这个答案并不声称是任何问题的某种神奇解决方案,它只是一个代码示例。使用它,或者不使用它。我认为如果使用得当,它会很方便。它包括扩展方法和反射的例子,也许有人可以从中学习。
5赞 JDB 3/26/2014
你试过吗?var x = double.TryParse("2.2", new double()) ? double.Parse("2.2") : 0.0;
2赞 Hein Andre Grønnestad 10/22/2015
是的,它不起作用。 如果你指定了你得到的.Argument 2 must be passed with the 'out' keywordoutnewA ref or out argument must be an assignable variable
1赞 elpezganzo 8/25/2017
性能TryParse 比这里公开的所有都好。结果:TryParse 8 正则表达式 20 PHP IsNumeric 30 反射 TryParse 31 测试代码 dotnetfiddle.net/x8GjAF
9赞 Noctis 5/16/2014 #15

如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个)。

  • 没有正则表达式和
  • 尽可能使用 Microsoft 的代码

您还可以执行以下操作:

public static bool IsNumber(this string aNumber)
{
     BigInteger temp_big_int;
     var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
     return is_number;
}

这将解决通常的讨厌问题:

  • 开头减号 (-) 或加号 (+)
  • 包含十进制字符BigIntegers 不会解析带有小数点的数字。(所以:会抛出一个异常,同样会返回 false)BigInteger.Parse("3.3")TryParse
  • 没有有趣的非数字
  • 涵盖数量大于通常使用量的情况Double.TryParse

你必须添加一个对你的类的引用,并在你的类之上(好吧,第二个是我猜:)System.Numerics using System.Numerics;

299赞 Kunal Goel 10/20/2014 #16

您还可以使用:

using System.Linq;

stringTest.All(char.IsDigit);

它将返回所有数字 (not ) 以及输入字符串是否为任何类型的字母数字。truefloatfalse

测试用例 返回值 测试结果
"1234" ✅通过
"1" ✅通过
"0" ✅通过
"" ⚠️失败(已知边缘情况)
"12.34" ✅通过
"+1234" ✅通过
"-13" ✅通过
"3E14" ✅通过
"0x10" ✅通过

请注意:不应为空字符串,因为这将通过数字测试。stringTest

评论

34赞 dan-gph 6/5/2015
这很酷。但有一点需要注意:空字符串将作为数字通过该测试。
2赞 Kunal Goel 6/6/2015
@dan-gph : 我很高兴,你喜欢它。是的,你是对的。我已经更新了上面的注释。谢谢!
3赞 Salman Hasrat Khan 2/24/2016
这也不适用于十进制大小写。正确的测试是 stringTest.All(l => char。IsDigit(l) ||'.' == l ||'-' == l);
1赞 Kunal Goel 2/26/2016
感谢您的输入 Salman,要专门检查字符串中的十进制,您可以 - if (Decimal.TryParse(stringTest2, out value)) { /* 是的,十进制 / } else { / 否,不是小数*/ }
9赞 Flynn1179 4/11/2016
萨尔曼,没那么简单——这将作为一个有效的数字传递。显然不是。..--..--
15赞 cyberspy 9/29/2015 #17

我知道这是一个旧线程,但没有一个答案真正为我做过——要么效率低下,要么没有封装以便于重用。我还想确保如果字符串为空或 null,则返回 false。在这种情况下,TryParse 返回 true(空字符串在分析为数字时不会导致错误)。所以,这是我的字符串扩展方法:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

简单易用:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

或者,如果要测试其他类型的数字,可以指定“样式”。 因此,要使用指数转换数字,您可以使用:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

或者,要测试潜在的十六进制字符串,可以使用:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

可选的“culture”参数可以以大致相同的方式使用。

它受到的限制是无法转换太大而无法包含在双精度值中的字符串,但这是一个有限的要求,我认为如果您正在处理比这更大的数字,那么无论如何您都可能需要额外的专用数字处理函数。

评论

2赞 Harald Coppoolse 11/16/2015
效果很好,只是 Double.TryParse 不支持 NumberStyles.HexNumber。请参阅 MSDN Double.TryParse。在检查 IsNullOrWhiteSpace 之前尝试解析的任何原因?如果 IsNullOrWhiteSpace 不这样做,TryParse 将返回 false?
2赞 2Yootz 11/10/2017 #18

使用 c# 7 it,您可以内联 out 变量:

if(int.TryParse(str, out int v))
{
}
2赞 userSteve 7/3/2018 #19

使用这些扩展方法可以清楚地区分检查字符串是否为数字,以及字符串是否仅包含 0-9 位数字

public static class ExtensionMethods
{
    /// <summary>
    /// Returns true if string could represent a valid number, including decimals and local culture symbols
    /// </summary>
    public static bool IsNumeric(this string s)
    {
        decimal d;
        return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
    }

    /// <summary>
    /// Returns true only if string is wholy comprised of numerical digits
    /// </summary>
    public static bool IsNumbersOnly(this string s)
    {
        if (s == null || s == string.Empty)
            return false;

        foreach (char c in s)
        {
            if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
                return false;
        }

        return true;
    }
}
2赞 OMANSAK 7/31/2018 #20
public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}
14赞 Dayán Ruiz 10/19/2018 #21

库纳尔·诺埃尔答案的更新

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

但是,对于这种情况,我们有空字符串将通过该测试,因此,您可以:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

评论

3赞 Rosdi Kasim 11/25/2020
这是更好的答案,因为它实际上不会将字符串转换为整数,并且存在整数溢出的风险。
7赞 Liakat Hossain 12/8/2018 #22

具有 .net 内置函数的最佳灵活解决方案称为 - 。它适用于无限的长数字。仅当每个字符都是数字时,它才会返回 true。我用了很多次,没有任何问题,而且我发现的解决方案更干净。我做了一个示例方法。它随时可以使用。此外,我还添加了对 null 和空输入的验证。所以这种方法现在是完全防弹的char.IsDigit

public static bool IsNumeric(string strNumber)
    {
        if (string.IsNullOrEmpty(strNumber))
        {
            return false;
        }
        else
        {
            int numberOfChar = strNumber.Count();
            if (numberOfChar > 0)
            {
                bool r = strNumber.All(char.IsDigit);
                return r;
            }
            else
            {
                return false;
            }
        }
    }

评论

0赞 Umar T. 7/22/2022
str.All(Char.IsDigit) 将声明“3.14”为假,以及“-2”和“3E14”。更不用说:“0x10”(正如 BlackTigerX 在上面的答案中评论的那样)
6赞 Tahir Rehman 7/23/2019 #23

尝试下面定义的正则表达式

new Regex(@"^\d{4}").IsMatch("6")    // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)

评论

1赞 geriwald 2/2/2021
谢谢,这对我来说是完美的解决方案
0赞 geriwald 2/2/2021
我需要测试 PIN 码的有效性,4 位数字,没有 0:new Regex(@“^[132465798]{4}”)。IsMatch(pin.文本)
1赞 Epic Speedy 3/29/2021
这应该是公认的答案。您不必将字符串转换为数字来执行此操作,因为如果它太长,它就会溢出。
0赞 Tahir Rehman 3/30/2021
@EpicSpeedy我的回答为时已晚
0赞 Nayan_07 8/23/2019 #24

所有的答案都是有用的。但是,在寻找数值为 12 位或更多(在我的情况下)的解决方案时,在调试时,我发现以下解决方案很有用:

double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);

结果变量将给出 true 或 false。

2赞 Yawar Ali 9/2/2021 #25
Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);

要检查字符串是 uint、ulong 还是只包含数字 1 。(点)和数字 示例输入

123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False
-2赞 M.Max 2/3/2023 #26

您可以在 ASCII 表中检查字符串的每个字符的序列号。 在 ASCII 表中,字符 '0'、'1',...'9' 它们按顺序排列,位置编号为 48、49,....57(十进制)。

象征 ... '.' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' ...
指数 ... 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 ...

通过比较输入字符串中的字符,我们比较它们在 ASCII 表中的索引,并可以找出它是否引用了数字。如果整个字符串仅由数字组成,则它是一个数字。还添加了对单个分隔符 ('.') 的出现检查。

 bool IsNumber(string str, char delimiter = '.')
    {
        if(str.Length==0) //Empty
        {
            return false;
        }
        bool isDelimetered = false;
        foreach (char c in str)
        {
            if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
            {
                return false;
            }
            if (c == delimiter)
            {
                if (isDelimetered) //more than 1 delimiter
                {
                    return false;
                }
                else //first time delimiter
                {
                    isDelimetered = true;
                }
            }
        }
        return true; 
    }

评论

3赞 Jeremy Caney 2/9/2023
请记住,Stack Overflow 不仅旨在解决眼前的问题,还旨在帮助未来的读者找到类似问题的解决方案,这需要了解底层代码。这对于我们社区中不熟悉语法的初学者来说尤其重要。鉴于此,您能否编辑您的答案以包括对您正在做的事情以及为什么您认为这是最佳方法的解释?这在这里尤为重要,因为现有答案有 20 多个,其中一个有近 1,500 个赞成票。
0赞 General Grievance 2/9/2023
它适用于问题中的输入,但是......对于必须完成的编码量来说,它非常有限,并且不能很好地扩展新功能。例如,既然你想识别小数点,为什么不包括指数或+/-符号呢?此外,这是 C#,因此请将您的方法名称大写并在您的标识符中使用 camel/Pascal 大小写而不是 .e_
0赞 M.Max 5/31/2023
这里提供了许多使用 TryParse 的解决方案。TryParse 效果很好,但它就像魔术一样,您可以立即获得结果。我提出了一个替代方案,也许有人会对此感兴趣。
0赞 Azaz ul haq 11/29/2023 #27

我发现最简单的 int 比较是

私有 bool IsNumeric(字符串文本) { 布尔值结果 = 文本。全部(字符。IsDigit); 返回 isNum;}