2016-05-11 34 views
0

我有一個文本框,我想驗證它匹配的模式車牌 = [X]__[####]_[ZZZ]我想製作一些匹配下面格式的驗證字符串

  • [X] =一個大寫字母
  • _ =空間
  • [####] =四位數字
  • [ZZZ] =三個大寫字母

例子:A 1234 BCD

怎麼辦我設置了驗證以匹配這個在一個文本框?

這是我的代碼,根據先生迪米特里

private void isvalidplate(string a) 
    { 
     if (a[0] < 'A' && a[0] > 'Z') 
     { 
      MessageBox.Show("Car Plate is invalid!"); 
     } 
     else if (a[1] != ' ' && a[5] != ' ') 
     { 
      MessageBox.Show("Car Plate is invalid!"); 
     } 
     else if (a[2] != Int64.Parse(a) && a[3]!= Int64.Parse(a) && a[4]!= Int64.Parse(a)) 
     { 
      MessageBox.Show("Car Plate is invalid!"); 
     } 
     else if ((a[6] < 'A' && a[6] > 'Z')&&(a[7] < 'A' && a[7] > 'Z')&&(a[8] < 'A' && a[8] > 'Z')&&(a[9] < 'A' && a[9] > 'Z')) 
     { 
      MessageBox.Show("Car Plate is invalid!"); 
     } 
    } 

,但它顯示一個錯誤,「輸入字符串的不正確的格式」 的錯誤是在這一行

else if (a[2] != Int64.Parse(a) && a[3]!= Int64.Parse(a) && a[4]!= Int64.Parse(a)) 
+1

[你到目前爲止嘗試過什麼?](http://whathaveyoutried.com) 請[編輯]你的問題以顯示代碼爲 的[mcve]你有問題,然後我們可以嘗試幫助 具體問題。你還應該閱讀[問]。 –

+0

使用正則表達式,並且模式:'[AZ] {1} \ d {4} [AZ] {3}' – SeM

回答

0

常見的在許多語言中用於字符串驗證和解析的工具是正則表達式(通常稱爲正則表達式)。習慣於使用它們作爲開發者非常方便。一個正則表達式匹配,你需要什麼樣子:

^[A-Z]\s\d{4}\s[A-Z]{3}$ 

This site顯示在行動您正則表達式。在C#中,你可以使用Regex庫測試你的字符串:

bool valid = Regex.IsMatch(myTestString, @"^[A-Z]\s\d{4}\s[A-Z]{3}$"); 

有網上學習正則表達式噸資源。

+0

我忘了提前,我的講師不允許使用正則表達式先生:( –

+2

Bah。如果這是家庭作業,那麼你將不得不表現出努力,而不是僅僅要求回答。 – Jonesopolis

+0

Sp你必須實現一個明確的測試:public static String IsCarPlateValid(String value){String.IsNullOrEmpty(value )) return false; if(value.Length!= 9) return false; ...返回true;}' –

0

所以,你必須實現明確測試:

public static String IsCarPlateValid(String value) { 
    // we don't accept null or empty strings 
    if (String.IsNullOrEmpty(value)) 
    return false; 

    // should contain exactly 11 characters 
    // letter{1}, space {2}, digit{4}, space{1}, letter{3} 
    // 1 + 2 + 4 + 1 + 3 == 11 
    if (value.Length != 11) 
    return false; 

    // First character should be in ['A'..'Z'] range; 
    // if it either less than 'A' or bigger than 'Z', car plate is wrong 
    if ((value[0] < 'A') || (value[0] > 'Z')) 
    return false; 

    //TODO: it's your homework, implement the rest 

    // All tests passed 
    return true; 
} 

測試您的實現,您可以使用正則表達式:

Boolean isValid = Regex.IsMatch(carPlate, "^[A-Z]{1} {2}[0-9]{4} {1}[A-Z]{3}$"); 

具有明顯的含義:一個字母,兩個空間,四位數字,一個空格,三個字母。

+0

我編輯過我的代碼,但是顯示錯誤當我嘗試將值解析爲int時,我的代碼出錯了先生? –

+0

@Andreas Gustavian:請使用* char * s,而不是* int * s,例如('value [3] <'0')||(value [3]>'9'))MessageBox.Show(「不是數字!」) );' –

+0

我明白了!謝謝你該死的先生! –