Sponsored Ad

Thursday, October 22, 2009

C# Regex.Replace

To use Regex & the delegate method MatchEvaluator for complex pattern replacements. You have a C# string with lowercased words & need to have uppercased ones; simple Regexes are not powerful . Solution. Here they see an example of using this regular expression code, using the C# programming language.

Here we look at an example of using MatchEvaluator. With regular expressions, you can specify a MatchEvaluator. This is a delegate process that the Regex.Replace process will call when you need to modify the match. Here we see how you can use MatchEvaluator to uppercase matches. This article is based on .NET 3.5 SP1.

Program that capitalizes strings (C#)

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // Input strings.
        const string s1 = "samuel allen";
        const string s2 = "dot net perls";
        const string s3 = "Mother teresa";

        // Write output strings.
        Console.WriteLine(TextTools.UpperFirst(s1));
        Console.WriteLine(TextTools.UpperFirst(s2));
        Console.WriteLine(TextTools.UpperFirst(s3));
    }
}

public static class TextTools
{
    /// <summary>
    /// Uppercase first letters of all words in the string.
    /// </summary>
    public static string UpperFirst(string s)
    {
        return Regex.Replace(s, @"\b[a-z]\w+", delegate(Match match)
        {
            string v = match.ToString();
            return char.ToUpper(v[0]) + v.Substring(1);
        });
    }
}

Output of the program

Samuel Allen
Dot Net Perls
Mother Teresa

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers