Regex.Match – this might save you 5 minutes of head-scratching

I often make use of the Regex.IsMatch( string ) method to check if a regular expression finds a match in a given string, however I do not often use the Match( string ) method which, unsurprisingly, returns an instance of Match. Matches( string ) returns a MatchCollection. Very handy.

But what does the Match( string ) method do if there is no match? You might be left scratching your head over this if you look at the documentation since it seems quite reluctant to reveal this precious secret. I initially wondered if it might just return null, but it doesn’t say so and this made me uneasy enough to take a little time to investigate further. If you look at the Match class itself you will find the Success property, which indicates whether or not the match succeeded. This seems to be exactly what you need, however I was still suspicious so I hacked together the world’s shortest NUnit test case and whacked a breakpoint on the call to Match( string ) in order to inspect the return value. Much to my relief it turned out that my non-matching regular expression returned a match with Success set to false.

If you instead call Matches( string ) with a string that does not match you will get back an empty MatchCollection, which is perfect and exactly what you would expect (the documentation is much clearer on this point, which is also good).