如果我有这些字符串:
"abc" = false
"123" = true
"ab2" = false
是否有一个命令,比如IsNumeric()或其他东西,可以识别字符串是否是有效数字?
我根本没有使用正则表达式,所以我很难排除故障.我希望正则表达式只在包含的字符串是所有数字时匹配; 但是下面的两个例子是匹配一个包含所有数字的字符串加上一个等号"1234 = 4321".我确信有一种方法可以改变这种行为,但正如我所说,我从未真正对正则表达式做过多少工作.
string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}
Run Code Online (Sandbox Code Playgroud)
如果重要,我正在使用C#和.NET2.0.
我经常Char.IsDigit用来检查a char是否是一个在LINQ查询中特别方便的数字,以便int.Parse在此处进行预检:"123".All(Char.IsDigit).
但是有些字符是数字,但无法解析为int喜欢?.
// true
bool isDigit = Char.IsDigit('?');
var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
int num;
// false
bool isIntForAnyCulture = cultures
.Any(c => int.TryParse('?'.ToString(), NumberStyles.Any, c, out num));
Run Code Online (Sandbox Code Playgroud)
这是为什么?我的int.Parse-precheck Char.IsDigit因此不正确吗?
有310个字符是数字:
List<char> digitList = Enumerable.Range(0, UInt16.MaxValue)
.Select(i => Convert.ToChar(i))
.Where(c => Char.IsDigit(c))
.ToList();
Run Code Online (Sandbox Code Playgroud)
这是Char.IsDigit.NET 4(ILSpy)中的实现:
public static bool IsDigit(char c)
{
if (char.IsLatin1(c))
{
return c >= '0' && c <= '9';
}
return …Run Code Online (Sandbox Code Playgroud) 如何检查.NET中的给定字符串是否为数字?
test1 - 是字符串
1232 - 是号码
test - 是字符串
tes3t - 是字符串
2323k - 是字符串
4567 - 是号码
如何使用系统功能执行此操作?