9/9/10

String replace using Regex

I recently ran into a situation where I had to highlight a certain word in a paragraph of text. Let us say the word is "Soccer". All I was trying to do was replace all occurences of "Soccer" with "Soccer" so that the word "Soccer" would get displayed in bold.

I initially thought of using the Replace method of the string class, but then quickly realised that Replace method is case-sensitive, so words like "sOccer" or "SOCCER" or "soccER" were not going to be replaced.

After some research on the web, i came across the Replace method of the Regex class(namespace - System.Text.RegularExpressions) that had the following signature:

public string Replace(string input,MatchEvaluator evaluator)

where input is the paragraph of text in which I wish to replace the word "Soccer".

The MatchEvaluator is a delegate with the following signature:

public string MatchEvaluatorMethod(Match match)

The code is as follows:

string TextToSearch = "The Soccer world cup was held in South Africa. There were 25 SOccer teams from all oover the world. It was a real treat for SOCCER fans all around the world";

//pattern to search is "Soccer"
Regex objRegex = new Regex("Soccer",RegexOptions.IgnoreCase);
 
string HighlightedText = objRegex.Replace(TextToSearch, new MatchEvaluator(HighlightWord));

/*The replace method calls the HighlightWord method every time it finds a match for the word "Soccer" in the TextToSearch and it is NOT case-sensitive. The input parameter to this method is an instance of the Match class that represents a match for the word "Soccer". The value returned from this method is then used to replace the matching word in the original string.*/

/*The end result "HighlightedText" is the same as the original text "TextToSearch", but with all the occurences of the word "Soccer" highlighted.*/

The method HighlightWord is as shown below:


//This method returns the highlighted word
public string HighlightWord(Match objMatch)
{
   string WordToHighlight = objMatch.ToString();
   return string.Format("{0}", WordToHighlight);
}

No comments: