2010-07-15 4 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] + "=", ""); –