2012-10-29 46 views

回答

2
if (Regex.IsMatch(input, "^[0-9]+$")) 
    .... 
+0

哪' 「^ \ d + $」'和' 「^ [0-9] + $」'是更正確? – CJ7

+0

實際上,當您談及「數字字符」時,'^ \ d + $'看起來更爲正確,其中包括'-','+',小數分隔符等。 –

1

您可以使用Char.IsDigitChar.IsNumber

var isNumber = str.Length > 0 && str.All(c => Char.IsNumber(c)); 

(記得要加using System.Linq;Enumerable.All或使用循環代替)

或使用int.TryParse代替(或double.TryParse等):

bool isNumber = int.TryParse(str, out number); 
+0

int.TryParse不適用於此問題,因爲它在字符串包含短劃線(負數)時返回true。所以這裏只有第一個解決方案是正確的。 –

+0

@ kor_:但是,問題不是很清楚,我不確定負數是否應該被視爲不是數字。 –

+0

我認爲這個問題很清楚。他想檢查一個字符串是否包含「僅數字字符」。也許他想驗證一些產品id? –

0

你可以使用正則表達式:

[TestCase("1234567890", true)] 
[TestCase("1234567890a", false)] 
public void NumericTest(string s, bool isnumeric) 
{ 
    var regex = new Regex(@"^\d+$"); 
    Assert.AreEqual(isnumeric, regex.IsMatch(s)); 
} 
+0

哪個'「^ \ d + $」'和'「^ [0-9] + $」'更正確? – CJ7

1

如果你在幾個地方做這個,在String類中添加一個擴展方法。

namespace System 
{ 
    using System.Text.RegularExpressions; 

    public static class StringExtensionMethods() 
    { 
     public static bool IsNumeric(this string input) 
     { 
      return Regex.IsMatch(input, "^[0-9]+$"); 
     } 
    } 
} 

然後,你可以使用這樣的:

string myText = "123"; 

if (myText.IsNumeric()) 
{ 
    // Do something. 
} 
相關問題