Irshad
Irshad

Reputation: 3131

Regex for two characters

How to construct a Regex to allow enter CA or CH? Tried \bC(A|H) and C(A|H) but I need to validate it in the KeyPress event of the textbox like this;

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;
}

Upvotes: 1

Views: 156

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627056

You can use

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

Inside the KeyPress event handler, txtCaCh.Text contains the value before adding the next key. So, to get the full value we need to add the newly pressed key value. After that, we can check if the value is the one we can accept.

^C[AH]?$

This regex accepts C or CA or CH values, so that we can type them in.

Then, you need to validate it at some other event with ^C[AH]$ (Leave event, for example).

Live validation cannot be performed at the same time as final validation.

Upvotes: 3

Pavel Pája Halbich
Pavel Pája Halbich

Reputation: 1583

Your pattern must be ^C[AH]$. Start of input (^), folowing C, then A or H ([AH])and end of input ($).

private Regex _regex = new Regex(@"^C[AH]$");

private void txtCaCh_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsControl(e.KeyChar))
        return;

    var txtBox = (TextBox)sender;
    if (txtBox.Text != null && _rolfRegex.IsMatch(txtBox.Text.ToUpper()))
    {
        // TODO now we have match, handle it
    }
}

Upvotes: 1

Dan Davies Brackett
Dan Davies Brackett

Reputation: 10071

instead of validating the e.KeyChar, validate the content of the control itself:

if(!_rolfRegex.IsMatch((sender as TextBox)?.Value.ToUpper())
    e.Handled = true;

Upvotes: 2

Related Questions