2013-06-05 24 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); 
    }