如何用c#更有效地操作字符串



原始字符串
它由三部分组成:

1- words(中文)
2- [img]pic url[/img]
3-[url]url[/url]
4-



结果如下所示:

sometextsometextsometextsometextsometextsometext
[img] http://www.a.com/a.jpg [/img] othertextothertextothertextothertextothertext [img] http://c.b.com/a.jpg [/img] anothertextanothertextanothertextanothertextanothertext [url] http://d.e.f [/url] alwaystext [img] http://f.g.com/a.gif [/img] [img] http://d.e.net/a.png [/img]

我想要的
仍然由3部分组成,但有一点变化:

1- words
2 - & lt;Img src="pic url" width="300">
3 - & lt;A href="url">url


我现在做什么

//content is the source string
string[] contentArray = Regex.Split(content, @"[img](.+?)[/img]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
StringBuilder sb= new StringBuilder();
foreach (string item in contentArray)
{
    //if it is a pic url
    if (item.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &
        (item.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
         item.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
         item.EndsWith(".png", StringComparison.OrdinalIgnoreCase)))
    {
       //convert it into a < img> link
       //append to sb
    }
    else
    {
       string[] contentArray1 = Regex.Split(item, @"[url](.+?)[/url]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
       foreach (string tmpItem in ContentArray)
       {
           if (it is a URL)
           {
              //convert it into a < a> link
              //append to sb
           }
           else //must be normal text
           {
                //to make a better layout
                //put into a < p>
                //append to sb
           }
       }
    }
}


上面的代码是有效的,但是,有更好的解决方案吗?我这里所说的"更好的解决方案"是指更快的速度@_@

一种编码方法是使用Match。替换为MatchEvaluator委托。注意,在访问match时会有不同的索引。为[url]和[img]分组项,因为它们对应于原始reg中的不同组。表达式。

    public static string ReplaceTags(Match match)
    {
        if (match.Value.StartsWith("[url]") && match.Groups.Count == 4)
            return String.Format("<a href="{0}">{0}</a>", match.Groups[2]);
        else if (match.Value.StartsWith("[img]") && match.Groups.Count == 4)
            return String.Format("<img src="{0}" width="300">", match.Groups[3]);
        throw new Exception("Unknown match found. Deal with it.");
    }
    static void Main(string[] args)
    {
        string text = "text[url]http://some_url[/url]text2[img]http://some/img.jpg[/img]text3";
        Regex regex = new Regex(@"([url](.*)[/url]|[img](.*)[/img])");
        string result = regex.Replace(text, ReplaceTags);
        Console.WriteLine(result);
    }

最新更新