开发者

C# regular expression to find custom markers and take content

开发者 https://www.devze.com 2023-01-24 22:00 出处:网络
I have a string: productDescription In it are some custom tags such as: [MM][/MM] For example the string might read:

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 e开发者_如何学Pythonxpression 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


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";
});


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";


A regex like this

\[(\w+)\](\d+)\[\/\w+\]

will find and collect the units (like MM) and the values (like 1000). That would at least allow you to use the pairs of parts intelligently to do the conversion. You could then put the replacement string together, and do a straightforward string replacement, because you know the exact string you're replacing.

I don't think you can do a simple RegEx.Replace, because you don't know the replacement string at the point you do the search.


    Regex rex = new Regex(@"\[MM\]([0-9]+)\[\/MM\]");

    string s = "This product is [MM]1000[/MM] long";

    MatchCollection mc = rex.Matches(s);

Will match only integers.

    mc[n].Groups[1].Value;

will then give the numeric part of nth match.

0

精彩评论

暂无评论...
验证码 换一张
取 消