Published
Tuesday, August 15, 2006 11:40 AM
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).
You need to sign in to comment on this blog
About Bart Read
I've had a few jobs since graduating, but for the last four years I've been settled at Red Gate Software in Cambridge, UK. Over that time I've worked on a wide range of products, both as a developer and as a project manager, including 18 months on SQL Prompt; right now I'm finishing up with ANTS Profiler 4, which we think is going to be amazing - hopefully you will too.