2014-10-28 43 views
0

我想讓用戶輸入的文本框中的文本必須包含字符後跟數字。例如:A1001。如果文本框不包含字符後跟數字,我已經找到使用正則表達式的解決方案並顯示一個錯誤消息框,但是一旦我在文本框中輸入文本「A1」,錯誤消息框仍會出現。檢查文本框中是否包含任何字符和數字

這裏是我使用的代碼:

void button1_Click(object sender, EventArgs e) 
     { 
      if (!Regex.IsMatch(this.textBox1.Text, @"(a-zA-Z)")) 
      { 
       SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2); 
      } 

      else if (!Regex.IsMatch(this.textBox1.Text, @"(0-9)")) 
      { 
       SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2); 
      } 
     } 

你的回答非常感謝!

謝謝

+0

合併2分正則表達式的成1 [A-ZA-Z0-9] * – 2014-10-28 08:06:46

+0

什麼是'character'你嗎?給一些必須匹配的樣本字符串和一些不能的字符串。 – Toto 2014-10-28 08:18:33

回答

1
^[a-zA-Z]+\d+$ 

試試這個。這一個正則表達式將驗證你的條件。參見demo。

http://regex101.com/r/sU3fA2/25

+0

你的答案對我有用,上面提到的bug''AA1''也有效。謝謝。 – 2014-10-28 08:28:49

+0

@UnknownUser很高興它工作:) – vks 2014-10-28 08:29:07

2

整個表達式中使用正則表達式的一個:

if (!Regex.IsMatch(this.textBox1.Text, @"^[a-zA-z][0-9]+$")) 
{ 
    SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2); 
} 

這將匹配有一個字符後面跟着一個或多個數字組成的字符串。如果你想允許多個字符,你必須使用[a-zA-z]+

因爲我假設你只想在這個字段中輸入產品代碼,我還在字符串的末尾添加了^作爲開始和$。

+0

非常感謝!它的工作! – 2014-10-28 08:20:51

+0

如您所說發現了一個錯誤,當兩個字符後跟數字時,它將不匹配。 'AA1' – 2014-10-28 08:24:33

+0

@vks:你的回答對我有用,上面提到的「AA1」也有問題。謝謝。 – 2014-10-28 08:28:28

1

在表格,也可使用MaskedTextBox中,使用這種控制和掩碼屬性設置爲:

L0000 

這樣會強制用戶輸入一個字母(L)和4數字(0000)。當然,你可以按你想要的方式定製它。

例如LLL-000會給你3個字母后跟一個縮進和3個數字。

0

你的問題似乎有點混亂。 請試試這個按鈕內點擊

 if (!Regex.IsMatch(this.MyTextBox.Text, @"[A-C][0-9]{4}")) 
     { 
      SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2); 
     } 
相關問題