2010-07-15 96 views
0

下面的代碼輸出:如何從bbcode url標籤中提取url +參數?

http://www.google.com 
http://www.google.com&lang 

什麼是更改代碼,以便它輸出的最簡單方法:

http://www.google.com 
http://www.google.com&lang=en&param2=this&param3=that 

CODE:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace TestRegex9928228 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string text1 = "try out [url=http://www.google.com]this site (http://www.google.com)[/url]"; 
      Console.WriteLine(text1.ExtractParameterFromBbcodeUrlElement()); 

      string text2 = "try out [url=http://www.google.com&lang=en&param1=this&param2=that]this site (http://www.google.com)[/url]"; 
      Console.WriteLine(text2.ExtractParameterFromBbcodeUrlElement()); 

      Console.ReadLine(); 
     } 
    } 

    public static class StringHelpers 
    { 
     public static string ExtractParameterFromBbcodeUrlElement(this string line) 
     { 
      if (line == null) 
       return ""; 
      else 
      { 
       if (line.Contains("]")) 
       { 
        List<string> parts = line.BreakIntoParts(']'); 
        if (parts[0].Contains("=")) 
        { 
         List<string> sides = parts[0].BreakIntoParts('='); 
         if (sides.Count > 1) 
          return sides[1]; 
         else 
          return ""; 
        } 
        else 
         return ""; 
       } 
       else 
        return ""; 
      } 
     } 

     public static List<string> BreakIntoParts(this string line, char separator) 
     { 
      if (String.IsNullOrEmpty(line)) 
       return new List<string>(); 
      else 
       return line.Split(separator).Select(p => p.Trim()).ToList(); 
     } 
    } 
} 

回答

1

最簡單,最有效的?你似乎在問兩個不同的問題。最簡單的將是這樣的:

變化:

List<string> sides = parts[0].BreakIntoParts('='); 
if (sides.Count > 1) 
    return sides[1]; 

要:

List<string> sides = parts[0].BreakIntoParts('='); 
if (sides.Count > 1) 
    return parts[0].Replace(sides[0], ""); 

編輯:看起來你改變標題去掉 「最有效」。這是我看到的最簡單的更改(最少的代碼行)。

+0

謝謝,這是非常簡單的工作,以及我只是不得不添加一個等號:return parts [0] .Replace(sides [0] +「=」,「」); – 2010-07-15 16:32:04