Capturing a string in a specific format I have a requirement to capture a string in a specific format of * [Numeric Digits] *. This is how I have done right now but I think it would be faster with Regular Expressions. I don't have a lot of experience with RegEx, so please help me optimize this code using RegEx.

if (string.IsNullOrEmpty(BarcodeScan) &amp;&amp; e.KeyChar.ToString() == "*")
    BarcodeScan = e.KeyChar.ToString();
else
{
    if (BarcodeScan.StartsWith("*"))
    {
        if (int.TryParse(e.KeyChar.ToString(), out i))
            BarcodeScan += i.ToString();

        else if (e.KeyChar.ToString() == "*")
        {
            BarcodeScan += "*";
            ArticleID = BarcodeScan.Substring(1, BarcodeScan.Length - 2);
        }
        else            
            BarcodeScan = string.Empty;
     }
}


The above code is written in KeyPress event so I have to capture the string as the user is doing the input. Basically the first * means that the user has started entering Article ID and I keep on capturing numeric digits till he enters another *. 

This means that 


*2323 is valid but incomplete
*34h is invalid
*343f33 is invalid 
*3434hsds3 * is invalid
*3412 * is valid and complete


How do I check for *2323 in regex?  I tried ^\*\d+ but it allows *22f as well.
Could you possibly provide more samples of your data? In any case, try this 

Regex regex = new Regex(@"^[*]\d+[*]$");


If you actually expect the brackets (e.g. []) using the following:

Regex regex = new Regex(@"^[*][\[]\d+[]][*]$");