如何构造一个Regex 来允许输入CA 或CH? 尝试了 \bC(A|H) 和 C(A|H) 但我需要在 的 像这样;KeyPress 事件中验证它>文本框
private Regex _regex = new Regex(@"C(A|H)");
private void txtCaCh_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar))
return;
if (!_rolfRegex.IsMatch(e.KeyChar.ToString().ToUpper()))
e.Handled = true;
}
请您参考如下方法:
你可以使用
if (e.KeyChar != (char)8) // Not a backspace key
if (!Regex.IsMatch(txtCaCh.Text.ToUpper() + e.KeyChar.ToString().ToUpper(), @"^C[AH]?$")) // If the value is not CH or CA
e.Handled = true; // Do not let it pass
在 KeyPress 事件处理程序中,txtCaCh.Text 包含添加下一个键之前的值。因此,要获得完整的值,我们需要添加新按下的键值。之后,我们可以检查该值是否是我们可以接受的值。
^C[AH]?$
此正则表达式接受 C 或 CA 或 CH 值,以便我们可以输入它们。
然后,您需要使用 ^C[AH]$(例如 Leave 事件)在其他事件中验证它。
实时验证不能与最终验证同时执行。
