.NET Regular Expression Replacement

Regular expressions are commonly used to find patterns in strings, however they can also be used to replace parts of strings. Imagine that I have a requirement to find all of the headings in a html document and convert them to spans.

    

This is a heading

becomes This is a heading

 I can do this with regular expressions in .NET using the Regex.Replace method and  a MatchEvaluator:

    private void ReplaceHeadingsWithSpans() 
    { 
        var input = "<h1>This is a heading</h1>";
        var expression = new Regex(@"<h\d>(?<heading>[^<]+)</h\d>", RegexOptions.IgnoreCase);
        var result = expression.Replace(input, new MatchEvaluator(Replacement));
    }

    private static string Replacement(Match m)
    {
        var heading = m.Groups["heading"].Value;
        return "<span>" + heading + "</span>";
    }

The Replacement method will be called once for each heading found in the input. It extracts the text of the heading from the 'heading' named group and wraps it in a span.


Comments are closed