2008年7月2日星期三

Regular Expression

I started to play with regular expression since a few days ago. In .NET framework , there is a namespace System.Test.RegularExpressions where you can find helpful classes. Give you a simple sample, I wrote this for our project. Maybe this can help you start.

Senario:
We need user to input string in a text box, the string represent a frequency value, like "10.000 MHz".

Validation rule: (top down are the charaters can legally show in the string)
0 to N spaces
0 to N figure(0,1,2...9)
0 or 1 dot
1 to N figures
0 to N spaces
0 or 1 letter(the letter could be k, K, m, M, g, G)
0 or 1 letter(h or H)
0 or 1 letter(z or Z)
0 to N spaces.

C# Codes:
Regex r = new Regex(@"^\s*\d*[.]?\d+\s*[kKmMgG]?[hH]?[zZ]?\s*$");
Match m = r.Match(" 20000000000 ghz");
if (m.Success)
{
Console.WriteLine("Found match at position " + m.Index);
}


What simple! You can image how hard this could be when you just use CString, or string classes.

See detail about regular expression here.

没有评论: