>>Getting rid of the Regex ? You throw away all the fun ...
>
>:)
>
Frank,
Let me introduce you some fun
(1) I would use ^ and $ - otherwise the pattern may match other things than the intented
(2) The Regex class has some static methods (Match(), Matches(), IsMatch(), Replace() ) you can use without having to instantiate an object
It caches 15 recently used patterns - see CacheSize
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx(3) You can use Groups[ ].Value
string filepath = @"\folder\aaa.bb";
string pat = @"^.*\\(?:.+)\\(.+)\.(.+)$";
var m = Regex.Match(filepath, pat);
if (m.Success)
{
Console.WriteLine("{0}", m.Groups[1].Value); // aaa
Console.WriteLine("{0}", m.Groups[2].Value); // bb
}
else
Console.WriteLine("No match");
Console.ReadLine();
(4) The Groups[] collection can be indexed by
(a) a non-negative integer. I do not like this. You introduce another pair of parentheses somewhere and you've had it. The indexes have changed
(b) name. This is where named groups come in
string filepath = @"\folder\aaa.bb";
string pat = @"^.*\\(?:.+)\\(?<FileStem>.+)\.(?<FileExtension>.+)$";
var m = Regex.Match(filepath, pat);
if (m.Success)
{
Console.WriteLine("{0}", m.Groups["FileStem"].Value); // aaa
Console.WriteLine("{0}", m.Groups["FileExtension"].Value); // bb
}
else
Console.WriteLine("No match");
Console.ReadLine();
(5) You can even nest named groups
string filepath = @"\folder\aaa.bb";
string pat = @"^.*\\(?:.+)\\(?<FileName>(?<FileStem>.+)\.(?<FileExtension>.+))$";
var m = Regex.Match(filepath, pat);
if (m.Success)
{
Console.WriteLine("{0}", m.Groups["FileStem"].Value); // aaa
Console.WriteLine("{0}", m.Groups["FileExtension"].Value); // bb
Console.WriteLine("{0}", m.Groups["FileName"].Value); // aaa.bb
}
else
Console.WriteLine("No match");
Console.ReadLine();
(6) Let me also introduce zero-width assertions. They can be positive/negative and lookahead/lookbehind
An example: Validate a password, constraints are
(a) at least one lower case char
(b) at least one upper case char
(c) at least one digit
(d) at least 6 chars long
string[] test =
{ "1", //false
"2a", // false
"H1a4t", // false
"helloThere", // false
"hello1there", // false
"hello1There" // true
};
string pat = @"^((?=.*\d.*)(?=.*[a-z].*)(?=.*[A-Z].*).{6,})$";
foreach( var s in test )
{
var m = Regex.Match(s, pat);
Console.WriteLine("{0}: {1}", m.Success, s);
}
Console.ReadLine();
(7) Finally, if you want to discover more fun and goodies - there are plenty
http://msdn.microsoft.com/en-us/library/az24scfc.aspx
Gregory