2013-06-05 26 views
-1

原始字符串
它是由3个部分组成:
如何通过C#更有效地操作字符串?

1-字(中国)
2- [IMG] PIC URL [/ IMG]
3- [网址] URL [/ URL]
4- < BR>



所以结果是一样的东西下面:

sometextsometextsometextsometextsometextsometext < br> [img] http://www.a.com/a.jpg [/ img] othertextothertextothertextothertextothextxtrtextxtrtertextxtrtertext [img] http://cbcom/a.jpg [/ img] anothertextanothertextanothertextanothertextanothertext [url] http: //def[/url]alwaystext[img]http://fgcom/a.gif[/img][img]http://denet/a.png[/img]

我想要什么
仍然由3个部分组成,但稍加改变:

1-词语
2- < IMG SRC =“PIC URL” WIDTH = “300”>
3- < A HREF = “URL”> URL </A>


我现在在做什么

//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 
      } 
     } 
    } 
} 

存在的问题
上面的代码工作,但任何更好的解决方案?使其更有效我的意思是“更好的解决方案”在这里意味着更快的速度@ _ @

+0

那么你的解决方案是否工作?如果没有,那么它不起作用,如果它,你希望改善什么? – Servy

+0

@Servy我认为它*确实有效,但OP想知道,如果它不能更快​​。 – Nolonar

+0

@Nolonar现在还不清楚它是否有效,这就是我问过的原因,也不清楚他想如何改进它,他没有试图说明这一点。他可能希望它运行得更快,使用更少的内存,更具可读性,处理目前无法使用的输入,使用更少的代码或其他任何因素。 – Servy

回答

0

编码它的一种方法是用Match.Replace与MatchEvaluator委托。请注意,访问[url]和[img]的match.Groups项目时有不同的索引,因为它们对应于原始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); 
    }