Bart

Software Engineer - Red Gate Software

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

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


by Bart Read
Filed Under:

Comments

No Comments
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.

















<August 2006>
SuMoTuWeThFrSa
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789
Virtual Exchange Servers
 Microsoft now supports running Exchange Server 2007 in server virtualization environments, not just on... Read more...

Virtualizing Exchange: points for discussion
 With the increasing acceptance of the use of Virtualization as a means of providing server... Read more...

Encouraging .NET Reflector Add-ins
 Jason Haley is well-known for the resources he's provided to developers who wish to extend Reflector's... Read more...

Using .NET Reflector Add-ins
 .NET Reflector by itself is great, but it really comes into its own with the help of some add-ins. Here... Read more...

Unique Experiences!
 You'd have thought that a unique constraint was an easy concept - Not a bit of it; it can cause a lot... Read more...