提问人:Gold 提问时间:5/22/2009 最后编辑:Alexander AbakumovGold 更新时间:5/31/2023 访问量:1484453
确定字符串是否为数字
Identify if a string is a number
问:
如果我有这些字符串:
"abc"
=false
"123"
=true
"ab2"
=false
是否有命令(例如或其他命令)可以识别字符串是否为有效数字?IsNumeric()
答:
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 可以替换为它们各自的类型!
评论
public static bool IsNumeric(this string text) { double _out; return double.TryParse(text, out _out); }
您始终可以对许多数据类型使用内置的 TryParse 方法,以查看相关字符串是否会通过。
例。
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
结果将 = True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
结果将 = False
评论
可以使用 TryParse 来确定是否可以将字符串分析为整数。
int i;
bool bNum = int.TryParse(str, out i);
布尔值会告诉你它是否有效。
如果你想知道一个字符串是否是一个数字,你可以随时尝试解析它:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
请注意,返回一个 ,您可以使用它来检查解析是否成功。TryParse
bool
bool Double.TryParse(string s, out double result)
如果您不想使用 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;
}
}
评论
char
Member 'char.IsDigit(char)' cannot be accessed with an instance reference; qualify it with a type name instead
.All(c => char.IsDigit(c) || c == '.'))
这可能是 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(...)
评论
我已经多次使用这个函数:
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
(来源:aspalliance.com)
(来源:aspalliance.com)
评论
下面是 C# 方法。Int.TryParse 方法 (String, Int32)
如果全部为数字,则返回 true。不知道它是否比 更好,但它会起作用。input
TryParse
Regex.IsMatch(input, @"^\d+$")
如果您只想知道它是否将一个或多个数字与字符混合在一起,请省略 和 .^
+
$
Regex.IsMatch(input, @"\d")
编辑:实际上,我认为它比 TryParse 更好,因为很长的字符串可能会溢出 TryParse。
评论
RegexOptions.Compiled
Regex.IsMatch(x.BinNumber, @"^\d+$", RegexOptions.Compiled)
.
希望这会有所帮助
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
如果你想捕捉更广泛的数字,就像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"
评论
在项目中拉取对 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
评论
IsNumeric
9999999999999999999999999999999999999999999999999999999999.99999999999
True
我想这个答案只会在所有其他答案之间丢失,但无论如何,这里是。
我最终通过谷歌解决了这个问题,因为我想检查是否是,以便我可以使用它而不是方法。string
numeric
double.Parse("123")
TryParse()
为什么?因为在知道解析是否失败之前必须声明变量并检查结果很烦人。我想使用 来检查是否是,然后在第一个三元表达式中解析它或在第二个三元表达式中提供默认值。out
TryParse()
ternary operator
string
numerical
喜欢这个:
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 解析为任何方法,并且还允许您指定在转换失败时返回的默认值。string
type
TryParse()
这比将三元运算符与上述扩展方法一起使用要好,因为它只执行一次转换。不过,它仍然使用反射......
例子:
"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
评论
var x = double.TryParse("2.2", new double()) ? double.Parse("2.2") : 0.0;
Argument 2 must be passed with the 'out' keyword
out
new
A ref or out argument must be an assignable variable
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个)。
- 没有正则表达式和
- 尽可能使用 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;
您还可以使用:
using System.Linq;
stringTest.All(char.IsDigit);
它将返回所有数字 (not ) 以及输入字符串是否为任何类型的字母数字。true
float
false
测试用例 | 返回值 | 测试结果 |
---|---|---|
"1234" |
真 | ✅通过 |
"1" |
真 | ✅通过 |
"0" |
真 | ✅通过 |
"" |
真 | ⚠️失败(已知边缘情况) |
"12.34" |
假 | ✅通过 |
"+1234" |
假 | ✅通过 |
"-13" |
假 | ✅通过 |
"3E14" |
假 | ✅通过 |
"0x10" |
假 | ✅通过 |
请注意:不应为空字符串,因为这将通过数字测试。stringTest
评论
..--..--
我知道这是一个旧线程,但没有一个答案真正为我做过——要么效率低下,要么没有封装以便于重用。我还想确保如果字符串为空或 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”参数可以以大致相同的方式使用。
它受到的限制是无法转换太大而无法包含在双精度值中的字符串,但这是一个有限的要求,我认为如果您正在处理比这更大的数字,那么无论如何您都可能需要额外的专用数字处理函数。
评论
使用 c# 7 it,您可以内联 out 变量:
if(int.TryParse(str, out int v))
{
}
使用这些扩展方法可以清楚地区分检查字符串是否为数字,以及字符串是否仅包含 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;
}
}
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;
}
库纳尔·诺埃尔答案的更新
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
}
评论
具有 .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;
}
}
}
评论
尝试下面定义的正则表达式
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)
评论
所有的答案都是有用的。但是,在寻找数值为 12 位或更多(在我的情况下)的解决方案时,在调试时,我发现以下解决方案很有用:
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
结果变量将给出 true 或 false。
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
您可以在 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;
}
评论
e
_
我发现最简单的 int 比较是
私有 bool IsNumeric(字符串文本) { 布尔值结果 = 文本。全部(字符。IsDigit); 返回 isNum;}
评论