仅检查数字和一个可选小数点的字符串.

Man*_*esh 7 c# numeric

我需要检查一个字符串是否只包含数字.我怎样才能在C#中实现这一目标?

string s = "123"    ? valid 
string s = "123.67" ? valid 
string s = "123F"   ? invalid 
Run Code Online (Sandbox Code Playgroud)

有没有像IsNumeric这样的功能?

jsp*_*cal 10

double n;
if (Double.TryParse("128337.812738", out n)) {
  // ok
}
Run Code Online (Sandbox Code Playgroud)

工作假设数字不会溢出一倍

对于一个巨大的字符串,尝试正则表达式:

if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
  // ok
}
Run Code Online (Sandbox Code Playgroud)

如果需要,添加科学记数法(e/E)或+/-符号......

  • 不应该是Regex.IsMatch(),它返回一个bool,而不是Match(),它返回一个匹配? (2认同)