extract query string from a URL string

后端 未结 8 1508
抹茶落季
抹茶落季 2021-01-04 04:10

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

相关标签:
8条回答
  • 2021-01-04 04:24

    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

    0 讨论(0)
  • 2021-01-04 04:32

    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;
    }
    
    0 讨论(0)
  • 2021-01-04 04:34

    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));
    
    0 讨论(0)
  • 2021-01-04 04:40

    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

    0 讨论(0)
  • 2021-01-04 04:41

    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.

    0 讨论(0)
  • 2021-01-04 04:42

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

    0 讨论(0)
提交回复
热议问题