Sohan's Blog

Living the Developer's Life

A Good Example of C# Regular Expression: Implementing InitCap or Titleize/TitleCase Using C# and Regular Expression

Ever since I first learned about the regular expressions, I have always been fascinated by its magical capability. When I first learned about DFA/NFA, I figured out how it is possible to evaluate a regular expression and eventually, during my Undergrad at BUET, I implemented a regular expression evaluator for the Compiler Lab.

Now, given this history, here is a simple code that I wrote today. Let me know if you liked it-

Program()

{

Console.WriteLine(Titleize(“hello! This is a sample string for titleize!”));

Console.Read();

}

public string Titleize(string input)

{

return Regex.Replace(input.ToLower(), @”(?<space>\s*)(?<first>.)(?<rest>\S*)”, new MatchEvaluator(OnMatch));

}

public string OnMatch(Match match)

{

return string.Format(“{0}{1}{2}”, match.Groups[“space”].Value, match.Groups[“first”].Value.ToUpper(), match.Groups[“rest”].Value);

}

For a little explanation, the pattern @”(?<space>\s*)(?<first>.)(?<rest>\S*)” matches to a series of space followed by a word. The word is further divided into two parts, the first one is just the first character and the rest understandably captures the “rest” part of the word.

Next the OnMatch method takes each occurrence of a match of the above pattern and as shown, simply regroups the word as previous but just takes the Upper case of the first letter!

Simple? You got another good example of Regular Expression? Share with me.

Comments

Anonymous
The pattern could be much easier:
=======================================
public string Titleize(string input)
{ return Regex.Replace(input.ToLower(),
@"(?<first>\b\w),new MatchEvaluator(OnMatch));
}
public string OnMatch(Match match)
{ return match.Groups["first"].Value.ToUpper(); }
Sadique
Yes, this is a nice example of power of regular expression. Here is a nice article to learn quickly the grouping of match & several useful links of regular expression.