.NET 3.5 Extension Methods

I can't wait to start using extension methods in production. I've already thought of a few great uses for this. For a while I've been jealous of other languages and their seamless integration of regular expressions. Regular expressions are executed against strings, and so I feel it's appropriate to have them married together. With .NET 3.5, I can get a little bit closer with the following class:

    public static class StringExtensions
    {        
        private static Dictionary cache = new Dictionary();
        private static Regex cacheRegex(string r)
        {
            if (!cache.ContainsKey(r))
                cache[r] = new Regex(r, RegexOptions.Compiled);
            return cache[r];
        }

        public static bool IsMatch(this string s, string regex)
        {
            Regex r = cacheRegex(regex);
            return r.IsMatch(s);            
        }
        
        public static MatchCollection Matches(this string s,string regex){
            Regex r = cacheRegex(regex);
            return r.Matches(s);  
        }

        public static Match Match(this string s, string regex)
        {
            Regex r = cacheRegex(regex);
            return r.Match(s);
        }

        public static string[] Split(this string s, string regex)
        {
            Regex r = cacheRegex(regex);
            return r.Split(s);            
        }

        public static string Replace(this string s, string regex,string replacement)
        {
            Regex r = cacheRegex(regex);
            return r.Replace(s, replacement);
        }
    }

Sure, the caching could actually do something more useful, but the idea is there. Now I can do something like this:

"Josh".IsMatch("^J");

To me that is way better than this:

Regex startsWithJ=new Regex("^J");
startsWithJ.IsMatch("Josh");
  • http://jwab.net Joakim Westin

    Thanks a lot for this post!

    Well designed code that is often needed;-)