extract query string from a URL string

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 19:05:14

问题


I am reading from history, and I want that when i come across a google query, I can extract the query string. I am not using request or httputility since i am simply parsing a string. however, when i come across URLs like this, my program fails to parse it properly:

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

what i was trying to do is get the index of q= and the index of & and take the words in between but in this case the index of & will be smaller than q= and it will give me errors.

any suggestions?

thanks for your answers, all seem good :) p.s. i couldn't use httputility, not I don't want to. when i add a reference to system.web, httputility isn't included! it's only included in an asp.net application. Thanks again


回答1:


It's not clear why you don't want to use HttpUtility. You could always add a reference to System.Web and use it:

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

If that's not an option then perhaps this approach will help:

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

It splits on & and looks for the single split result that begins with "q=" and takes the substring at position 2 to return everything after the = sign. The assumption is that there will be a single match, which seems reasonable for this case, otherwise an exception will be thrown. If that's not the case then replace Single with Where, loop over the results and perform the same substring operation in the loop.

EDIT: to cover the scenario mentioned in the comments this updated version can be used:

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

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



回答2:


If you don't want to use System.Web.HttpUtility (thus be able to use the client profile), you can still use Mono HttpUtility.cs which is only an independent .cs file that you can embed in your application. Then you can simply use the ParseQueryString method inside the class to parse the query string properly.




回答3:


here is the solution -

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;
}



回答4:


Why don't you create a code which returns the string from the q= onwards till the next &?

For example:

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

int newIndex = s.IndexOf("&");

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

Cheers




回答5:


Use the tools available:

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:


If you really need to do the parsing yourself, and are only interested in the value for 'q' then the following would work:

        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);
            }
        }

But do try to look at using a proper URL parser, it will save you a lot of hassle in the future.

(amended this question to include a check for the '?' token, and support 'q' values at the end of the query string (without the '&' at the end) )




回答7:


And that's why you should use Uri and HttpUtility.ParseQueryString.




回答8:


HttpUtility is fine for the .Net Framework. However that class is not available for WinRT apps. If you want to get the parameters from a url in a Windows Store App you need to use WwwFromUrlDecoder. You create an object from this class with the query string you want to get the parameters from, the object has an enumerator and supports also lambda expressions.

Here's an example

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

You can also see http://www.dzhang.com/blog/2012/08/21/parsing-uri-query-strings-in-windows-8-metro-style-apps



来源:https://stackoverflow.com/questions/6082664/extract-query-string-from-a-url-string

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