在 WinForm 開發中,常需限制 TextBox 只能輸入字母(A-Z、a-z)和數字(0-9),禁止中文、特殊符號等非法字符。本文提供經實戰驗證的嚴謹正則方案。
^[0-9A-Za-z]*$
解析:
^:匹配字符串開始[0-9A-Za-z]:字符集,包含數字 0-9、大寫字母 A-Z、小寫字母 a-z*:匹配前面字符集零次或多次(允許空值;若必填請改用 +)$:匹配字符串結束在 TextBox 的 TextChanged 事件中驗證:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string pattern = @"^[0-9A-Za-z]*$";
if (!Regex.IsMatch(textBox1.Text, pattern))
{
// 移除最後輸入的非法字符
int selStart = textBox1.SelectionStart;
textBox1.Text = Regex.Replace(textBox1.Text, @"[^0-9A-Za-z]", "");
textBox1.SelectionStart = selStart - 1; // 修正光標位置
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// 允許控制鍵(退格、複製粘貼等)
if (char.IsControl(e.KeyChar)) return;
// 僅允許字母數字
if (!char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true; // 攔截輸入
}
}
// 類級別靜態編譯
private static readonly Regex _alphanumericRegex =
new Regex(@"^[0-9A-Za-z]*$", RegexOptions.Compiled);
採用「預攔截 + 事後清洗」雙重機制,能構建最健壯的輸入限制體系,滿足企業級應用的嚴格要求。