如果我有这些字符串:
"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可以被它们各自的类型替换!
如果input
是所有数字,这将返回 true。不知道它是否比 更好TryParse
,但它会起作用。
Regex.IsMatch(input, @"^\d+$")
如果您只想知道它是否有一个或多个数字与字符混合,请不要使用^
+
and $
。
Regex.IsMatch(input, @"\d")
编辑: 实际上我认为它比 TryParse 更好,因为很长的字符串可能会溢出 TryParse。
您还可以使用:
using System.Linq;
stringTest.All(char.IsDigit);
如果输入字符串是任何类型的字母数字,它将返回true
所有数字(不是float
) 。false
测试用例 | 返回值 | 测试结果 |
---|---|---|
"1234" |
真的 | ✅通过 |
"1" |
真的 | ✅通过 |
"0" |
真的 | ✅通过 |
"" |
真的 | ⚠️失败(已知的边缘情况) |
"12.34" |
错误的 | ✅通过 |
"+1234" |
错误的 | ✅通过 |
"-13" |
错误的 | ✅通过 |
"3E14" |
错误的 | ✅通过 |
"0x10" |
错误的 | ✅通过 |
请注意:stringTest
不应为空字符串,因为这将通过数字测试。
我已经多次使用此功能:
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# 中的最佳选择。
如果您想知道字符串是否包含整数(整数):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
TryParse 方法将尝试将字符串转换为数字(整数),如果成功,它将返回 true 并将相应的数字放入 myInt。如果不能,则返回 false。
使用int.Parse(someString)
其他响应中显示的替代方案的解决方案有效,但速度要慢得多,因为抛出异常非常昂贵。TryParse(...)
在版本 2 中被添加到 C# 语言中,在此之前您别无选择。现在你做了:因此你应该避免Parse()
替代方案。
如果要接受十进制数,decimal 类也有一个.TryParse(...)
方法。在上面的讨论中用十进制替换 int,同样的原则也适用。
您始终可以对许多数据类型使用内置的 TryParse 方法,以查看相关字符串是否会通过。
例子。
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
结果将 = True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
结果将 = False
如果您不想使用 int.Parse 或 double.Parse,您可以使用类似这样的方式自行开发:
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;
}
}
如果您想捕获更广泛的数字,例如 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 );
}
请记住,仅仅因为值是数字并不意味着它可以转换为数字类型。例如,"999999999999999999999999999999.9999999999"
是一个完全有效的数值,但它不适合 .NET 数值类型(不是标准库中定义的类型)。
我知道这是一个旧线程,但没有一个答案真的对我有用——要么效率低下,要么没有封装以便于重用。如果字符串为空或 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”参数。
它受限于无法转换太大而无法包含在双精度中的字符串,但这是一个有限的要求,我认为如果您使用大于此的数字,那么您可能需要额外的专门数字处理无论如何都起作用。
更新 Kunal Noel 答案
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
}
您可以使用 TryParse 来确定字符串是否可以解析为整数。
int i;
bool bNum = int.TryParse(str, out i);
布尔值会告诉你它是否有效。
如果你想知道一个字符串是否是一个数字,你总是可以尝试解析它:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
请注意,TryParse
返回 a bool
,您可以使用它来检查您的解析是否成功。
我想这个答案会在所有其他答案之间丢失,但无论如何,这里有。
我最终通过谷歌解决了这个问题,因为我想检查 a 是否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
}
我extension methods
为这些案例做了几个:
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;
}
此扩展方法允许您将 a 解析为具有方法的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
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个)。
你也可以这样做:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
这将解决通常的问题:
BigInteger.Parse("3.3")
会抛出异常,TryParse
同样会返回false)Double.TryParse
您必须添加对班级的引用System.Numerics
并
using System.Numerics;
在班级中名列前茅(好吧,我猜第二个是奖励:)
bool Double.TryParse(string s, out double result)
具有 .net 内置函数的最佳灵活解决方案 - char.IsDigit
。它适用于无限长数字。如果每个字符都是数字,它只会返回 true。我多次使用它,没有任何问题,而且我找到了更容易清洁的解决方案。我做了一个示例方法。它可以使用了。此外,我添加了对 null 和空输入的验证。所以这个方法现在是完全防弹的
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)
使用 c# 7,您可以内联 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;
}
希望这可以帮助
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
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 还是仅包含数字 one .(dot) 和 digits Sample 输入
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
在您的项目中引入对 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
所有的答案都是有用的。但是在寻找数值为 12 位或更多的解决方案时(在我的情况下),然后在调试时,我发现以下解决方案很有用:
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
结果变量会给你真或假。
这是 C# 方法。 Int.TryParse 方法(字符串,Int32)
//To my knowledge I did this in a simple way
static void Main(string[] args)
{
string a, b;
int f1, f2, x, y;
Console.WriteLine("Enter two inputs");
a = Convert.ToString(Console.ReadLine());
b = Console.ReadLine();
f1 = find(a);
f2 = find(b);
if (f1 == 0 && f2 == 0)
{
x = Convert.ToInt32(a);
y = Convert.ToInt32(b);
Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
}
else
Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
Console.ReadKey();
}
static int find(string s)
{
string s1 = "";
int f;
for (int i = 0; i < s.Length; i++)
for (int j = 0; j <= 9; j++)
{
string c = j.ToString();
if (c[0] == s[i])
{
s1 += c[0];
}
}
if (s == s1)
f = 0;
else
f = 1;
return f;
}