2009-06-25 149 views

回答

143

使用表達式:

^[a-zA-Z0-9]*$ 

即: 使用System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$"); 
if (r.IsMatch(SomeString)) { 
    ... 
} 
+0

如何在JavaScript中,同樣的事情,我猜? – mrblah 2009-06-26 00:25:08

+16

讓我們希望這隻用於英語國家...... – 2013-02-15 08:17:46

+2

如果您清理數據庫名稱或類似內部的東西,你不會在意它是否不會在英語國家運行。 – 2014-07-03 08:04:50

3

^\w+$將使a-zA-Z0-9_

使用^[a-zA-Z0-9]+$不允許下劃線。

注意,這兩個要求的字符串不爲空。使用*代替+允許空字符串。

31

你可以用一個擴展功能,而不是一個正則表達式做很容易...

public static bool IsAlphaNum(this string str) 
{ 
    if (string.IsNullOrEmpty(str)) 
     return false; 

    for (int i = 0; i < str.Length; i++) 
    { 
     if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i])))) 
      return false; 
    } 

    return true; 
} 

根據註釋:) ...

public static bool IsAlphaNum(this string str) 
{ 
    if (string.IsNullOrEmpty(str)) 
     return false; 

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c))); 
} 
18

雖然我認爲基於正則表達式的解決方案是大概是我走的路,我會試圖將它封裝在一個類型中。

public class AlphaNumericString 
{ 
    public AlphaNumericString(string s) 
    { 
     Regex r = new Regex("^[a-zA-Z0-9]*$"); 
     if (r.IsMatch(s)) 
     { 
      value = s;     
     } 
     else 
     { 
      throw new ArgumentException("Only alphanumeric characters may be used"); 
     } 
    } 

    private string value; 
    static public implicit operator string(AlphaNumericString s) 
    { 
     return s.value; 
    } 
} 

現在,當你需要一個有效的字符串,可以有方法的簽名需要AlphaNumericString,並知道如果你只有一個,它是有效的(除了空值)。如果有人試圖傳入未經驗證的字符串,則會產生編譯器錯誤。

你可以得到發燒友和執行所有平等的運營商,或從普通OL」字符串的顯式的AlphaNumericString的,如果你的關心。

147

在.NET 4.0中,你可以使用LINQ:

if (yourText.All(char.IsLetterOrDigit)) 
{ 
    //just letters and digits. 
} 

yourText.All將停止執行並返回false首次char.IsLetterOrDigit報告falseAll合同無法履行,然後。

注意!這個答案不嚴格檢查字母數字(通常爲A-Z,A-Z和0-9)。這個答案允許本地人物如åäö

更新2018年1月29日

上面只有語法當您使用具有正確類型的一個參數(在這種情況下char)單一方法的工作。

要使用多個條件,你需要這樣寫:

if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x))) 
{ 
} 
7

我需要檢查A-Z,A-Z,0-9;沒有正則表達式(儘管OP要求正則表達式)。

在這裏混合各種答案和評論,並從https://stackoverflow.com/a/9975693/292060討論,這測試字母或數字,避免其他語言字母,並避免其他數字,如分數字符。

if (!String.IsNullOrEmpty(testString) 
    && testString.All(c => Char.IsLetterOrDigit(c) && (c < 128))) 
{ 
    // Alphanumeric. 
} 
0

爲了檢查字符串既是一個字母和數字的組合,你可以重新寫@jgauffin答案使用.NET 4.0和LINQ如下:

if(!string.IsNullOrWhiteSpace(yourText) && 
(!yourText.Any(char.IsLetter) || !yourText.Any(char.IsDigit))) 
{ 
    // do something here 
} 
-6

我奉勸不依賴於現成的內置代碼在.NET框架,試圖提出新的解決方案..這就是我所做的..

public bool isAlphaNumeric(string N) 
{ 
    bool YesNumeric = false; 
    bool YesAlpha = false; 
    bool BothStatus = false; 


    for (int i = 0; i < N.Length; i++) 
    { 
     if (char.IsLetter(N[i])) 
      YesAlpha=true; 

     if (char.IsNumber(N[i])) 
      YesNumeric = true; 
    } 

    if (YesAlpha==true && YesNumeric==true) 
    { 
     BothStatus = true; 
    } 
    else 
    { 
     BothStatus = false; 
    } 
    return BothStatus; 
} 
相關問題