/// <summary>
/// 是否仅包含大写字母和数字
/// </summary>
public bool IsNumAndEnCh(string input)
{
const string pattern = @"^[A-Z0-9]+$";
var regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 仅保留TextBox中大写字母和数字
/// </summary>
public void StringFormat(TextBox textBox)
{
try
{
const string format = "[A-Z0-9]";
string value = textBox.Text.Trim();
if (string.IsNullOrWhiteSpace(value) || IsNumAndEnCh(value)) return;
MatchCollection results = Regex.Matches(value, format);
textBox.Text = results.Cast<object>().Aggregate<object, string>(null, (current, o) => current + o.ToString());
if (textBox.Text != value) textBox.SelectionStart = textBox.Text.Length;
}
catch (Exception ex)
{
Debug.WriteLine("格式化文本框内容出错:" + ex.Message);
}
}