如何从bbcode url标签中提取url +参数?

时间:2010-07-15 16:17:42

标签: c# regex parsing bbcode

以下代码输出:

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 个答案:

答案 0 :(得分: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], "");

修改:看起来您更改了标题以删除“效率最高”。这是我看到的最简单的变化(最少的代码行更改)。

相关问题