C# regular expression to find custom markers and take content

I have a string:

productDescription

In it are some custom tags such as:

[MM][/MM]

For example the string might read:

This product is [MM]1000[/MM] long

Using a regular expression how can I find those MM tags, take the content of them and replace everything with another string? So for example the output should be:

This product is 10 cm long


Solution 1:

I think you'll need to pass a delegate to the regex for that.

Regex theRegex = new Regex(@"\[MM\](\d+)\[/MM\]");
text = theRegex.Replace(text, delegate(Match thisMatch)
{

    int mmLength = Convert.ToInt32(thisMatch.Groups[1].Value);
    int cmLength = mmLength / 10;
    return cmLength.ToString() + "cm";
});

Solution 2:

Using RegexDesigner.NET:

using System.Text.RegularExpressions;

// Regex Replace code for C#
void ReplaceRegex()
{
    // Regex search and replace
    RegexOptions   options = RegexOptions.None;
    Regex          regex = new Regex(@"\[MM\](?<value>.*)\[\/MM\]", options);
    string         input = @"[MM]1000[/MM]";
    string         replacement = @"10 cm";
    string         result = regex.Replace(input, replacement);

    // TODO: Do something with result
    System.Windows.Forms.MessageBox.Show(result, "Replace");
}

Or if you want the orginal text back in the replacement:

Regex          regex = new Regex(@"\[MM\](?<theText>.*)\[\/MM\]", options);
string         replacement = @"${theText} cm";