从URL字符串中提取查询字符串

时间:2011-05-21 15:21:52

标签: c# string query-string

我正在阅读历史记录,我希望当我遇到谷歌查询时,我可以提取查询字符串。我没有使用请求或httputility,因为我只是解析一个字符串。但是,当我遇到这样的URL时,我的程序无法正确解析它:

http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google

我想要做的是得到q =的索引和&的指数并在两者之间取词,但在这种情况下,指数为&将小于q =,它会给我错误。

有什么建议吗?

感谢您的回答,一切似乎都很好:) p.s.我不能使用httputility,不是我不想。当我添加对system.web的引用时,不包括httputility!它只包含在asp.net应用程序中。再次感谢

8 个答案:

答案 0 :(得分:21)

目前尚不清楚为什么你不想使用HttpUtility。您可以随时添加对System.Web的引用并使用它:

var parsedQuery = HttpUtility.ParseQueryString(input);
Console.WriteLine(parsedQuery["q"]);

如果这不是一个选项,那么这种方法可能会有所帮助:

var query = input.Split('&')
                 .Single(s => s.StartsWith("q="))
                 .Substring(2);
Console.WriteLine(query);

它在&上拆分并查找以"q="开头的单个拆分结果,并在位置2处获取子字符串以返回=符号后面的所有内容。假设是存在单个匹配,这对于这种情况似乎是合理的,否则将抛出异常。如果不是这种情况,那么用Single替换Where,循环结果并在循环中执行相同的子字符串操作。

编辑以涵盖评论中提到的方案,可以使用此更新版本:

int index = input.IndexOf('?');
var query = input.Substring(index + 1)
                 .Split('&')
                 .SingleOrDefault(s => s.StartsWith("q="));

if (query != null)
    Console.WriteLine(query.Substring(2));

答案 1 :(得分:6)

如果您不想使用System.Web.HttpUtility(因此能够使用客户端配置文件),您仍然可以使用Mono HttpUtility.cs,它只是一个可以嵌入您的独立.cs文件应用。然后,您只需使用类中的ParseQueryString方法正确解析查询字符串。

答案 2 :(得分:4)

这是解决方案 -

string GetQueryString(string url, string key)
{
    string query_string = string.Empty;

    var uri = new Uri(url);
    var newQueryString = HttpUtility.ParseQueryString(uri.Query);
    query_string = newQueryString[key].ToString();

    return query_string;
}

答案 3 :(得分:3)

为什么不创建一个从q=开始直到下一个&返回字符串的代码?

例如:

  

string s = historyString.Substring(url.IndexOf(“q =”));

     

int newIndex = s.IndexOf(“&”);

     

string newString = s.Substring(0,newIndex);

干杯

答案 4 :(得分:2)

如果您确实需要自己进行解析,并且只对'q'的值感兴趣,那么以下内容将起作用:

        string url = @"http://www.google.com.mt/search?" +
            "client=firefoxa&rls=org.mozilla%3Aen-" +
            "US%3Aofficial&channel=s&hl=mt&source=hp&" +
            "biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";

        int question = url.IndexOf("?");
        if(question>-1)
        {
            int qindex = url.IndexOf("q=", question);
            if (qindex > -1)
            {
                int ampersand = url.IndexOf('&', qindex);
                string token = null;

                if (ampersand > -1)
                    token = url.Substring(qindex+2, ampersand - qindex - 2);
                else
                    token = url.Substring(qindex+2);

                Console.WriteLine(token);
            }
        }

但是,请尝试使用正确的URL解析器,这将为您节省很多麻烦。

(修改此问题以包括检查'?'标记,并在查询字符串末尾支持'q'值(最后没有'&'))

答案 5 :(得分:2)

使用可用的工具:

String UrlStr = "http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";

NameValueCollection Items = HttpUtility.ParseQueryString(UrlStr);

String QValue = Items["q"];

答案 6 :(得分:1)

这就是为什么你应该使用UriHttpUtility.ParseQueryString

答案 7 :(得分:1)

HttpUtility适用于.Net Framework。但是,该类不适用于WinRT应用程序。如果要从Windows应用商店应用中的URL获取参数,则需要使用WwwFromUrlDecoder。您可以使用要从中获取参数的查询字符串从此类创建对象,该对象具有枚举器并且还支持lambda表达式。

这是一个例子

var stringUrl = "http://localhost/?name=Jonathan&lastName=Morales";
var decoder = new WwwFormUrlDecoder(stringUrl);
//Using GetFirstByName method
string nameValue = decoder.GetFirstByName("name");
//nameValue has "Jonathan"

//Using Lambda Expressions
var parameter = decoder.FirstOrDefault(p => p.Name.Contains("last")); //IWwwFormUrlDecoderEntry variable type
string parameterName = parameter.Name; //lastName
string parameterValue = parameter.Value; //Morales

您还可以看到http://www.dzhang.com/blog/2012/08/21/parsing-uri-query-strings-in-windows-8-metro-style-apps