How to extract the url+parameters out of a bbcode url tag?

谁说胖子不能爱 提交于 2019-12-13 02:55:34

问题


The following code outputs:

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

What is the simplest way to change the code so it outputs:

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:


Simplest or most efficient? You're asking two different questions it seems. Simplest would be something like this:

Change:

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

To:

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

Edit: Looks like you changed title to remove "most efficient". Here's the simplest change (fewest lines of code changed) that I see.



来源:https://stackoverflow.com/questions/3257607/how-to-extract-the-urlparameters-out-of-a-bbcode-url-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!