//
you're reading...
.NET 1.x, .NET 2.0

preg_replace_callback in c#

Sometime today someone hit my blog after searching for “preg_replace_callback in c#”, this seems to be something useful to post about so here we go. And while this person is familiar with doing this stuff in PHP this post is for everyone so I’ll explain it from the ground up. If you are already familiar with preg_replace_callback in PHP then you can just look at the next line to see the key that unlocks the info in MSDN.

The magic of doing programmatic replacement of text in a .NET regular expression is handled by the MatchEvaluator delegate.

public delegate string MatchEvaluator( Match match );

When you write your Regex and use it in one of the Replace methods; every time your pattern has a match, that Match gets sent through the MatchEvaluator you specify. This delegate can point to any one of your methods that matches the right signature; and with it you can choose what to replace the found pattern with however you wish to.

For example: If you have the pattern \w+ it will match every series of word characters. Now we want to capitalize the first letter of every word; so we need to run some code to do that. This isn’t hard to do; but it requires more processing than I think Regex gives you by itself.

string CapitalizeWord( Match match )
{
  StringBuilder sb = new StringBuilder( match.Value );
  sb[0] = Char.ToUpper(sb[0]);  // Take the first letter, capitalize it, and set it back to the first letter.
 
  return sb.ToString();
}

Now combining that with what we learned above we can construct the proper use of the Regex object to do this.

using System;
using System.Text;
using System.Text.RegularExpressions;

class Program
{
  [STAThread]
  static void Main(string[] args)
  {
    string input = "";
    
    while( (input = Console.ReadLine()) != "" )
    {
      MatchEvaluator myMatchEvaluator = 
        new MatchEvaluator( CapitalizeWord );

      // the @ means \ doesn't escape anymore
      Regex re = new Regex( @"\w+" ); 
      string output = re.Replace( input, myMatchEvaluator );

      Console.WriteLine( "{0}", output );
    }
  }

  static string CapitalizeWord( Match match )
  {
    StringBuilder sb = new StringBuilder( match.Value );
    
    // Take the first letter, capitalize it, 
    // and set it back to the first letter.
    sb[0] = Char.ToUpper(sb[0]);  

    return sb.ToString();
  }
}
Advertisements

About James

I am a Senior Developer/Consultant for InfoPlanIT, LLC. I previously spent over 7 years as a Product Manager for what eventually became ComponentOne, a division of GrapeCity. While there, I helped to create ActiveReports 7, GrapeCity ActiveAnalysis, and Data Dynamics Reports.

Discussion

5 thoughts on “preg_replace_callback in c#

  1. Great information. I noticed that your regex expression should be @”\w+” instead of @”w+”

    Posted by Sam | August 9, 2006, 10:34 am
  2. Thanks Sam; it looks like its a glitch with wordpress though…when I view the original post the \ is in there….wonder why its taken out.

    Posted by james | August 9, 2006, 5:36 pm
  3. Thanks for information,

    This was very much useful for me.

    I was looking for this from some time.

    regards,

    Posted by Mandar | December 9, 2006, 7:29 am
  4. Great, very useful. Saved me loads of time.

    Posted by Jim | April 12, 2007, 11:24 am
  5. Many thanks for your capitalisation code, it will be used in our database called Platinum – download from website if interested. Thanks, Craig Kelly-Soens

    Posted by Craig Kelly-Soens | April 29, 2007, 4:45 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archive

%d bloggers like this: