# 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) && 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.

• This free tool is great for testing your expressions radsoftware.com.au/regexdesigner. I'm not associated with the company, just a grateful user :) – WileCau Dec 18 '11 at 10:57

Regex regex = new Regex(@"^[*]\d+[*]$");  If you actually expect the brackets (e.g. []) using the following: Regex regex = new Regex(@"^[*][\[]\d+[]][*]$");

• To check for *2323 use ^[*][\[]\d+$ – JoeGeeky Dec 18 '11 at 11:51 • it didnt work. What is the purpose of [\[] ? \d+$ means that there should be on or more numerics at the end? – Haris Dec 18 '11 at 11:59
• The [*] checks to ensure it starts with a '*'. The [\[] checks to ensure the next character is '['. The \d+ checks to ensure it has a series of digits. I ran a test for *[123 on regexplanet.com/advanced/dotnet/index.html and a match was found. Wait... Sorry, I misread your sample data you wanted to test *123. My bad... use ^[*]\d+\$ – JoeGeeky Dec 18 '11 at 12:31