blair260 blair260 -4 years ago 198
C# Question

How to find and Replace a token in a c# string that starts with a value

I've got an issue where I am applying a template to an object and am using a find and replace function to mesh the template in the form of a string of html. The issue is, the height and width of the image are contained in the token so I don't have a way to find and replace as it could vary.

Token value is [ARTICLEIMAGE:150:200]

foreach(var article in articles) {
var articleTemplateValue = _TemplateArticleMarkup;
articleTemplateValue = articleTemplateValue.Replace("[ARTICLEIMAGE:xx:yy]", "<img src=" + article.ArticleImageFolder + "/" + article.ArticleImage + " title=" + article.ArticleTitle + " width="
xx" height="
yy" />");
}


This obviously would not work for every example as the dimensions of the image token will vary. Is there a way to find the token as a StartsWith and then split the dimensions an array on the :. Please let me know if that makes sense as it is a little confusing. Thanks!

Answer Source

Regex will solve this issue for you.

using System.Text.RegularExpressions;

Then change your code as seen below.

foreach (var article in articles)
{
    string articleTemplateValue = _TemplateArticleMarkup;

    MatchCollection mc = Regex.Matches(articleTemplateValue, @"\[ARTICLEIMAGE\:(\d+)\:(\d+)\]");

    if (mc.Count > 0)
    {
        string toReplace = mc[0].Value;
        string xx = mc[0].Groups[1].Value;
        string yy = mc[0].Groups[2].Value;

        articleTemplateValue = articleTemplateValue.Replace(toReplace, "<img src=\"" + article.ArticleImageFolder + "/" + article.ArticleImage + "\" title=\"" + article.ArticleTitle + "\" width=\"" + xx + "\" height=\"" + yy + "\"/>");
     }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download