extract query string from a URL string

后端 未结 8 1620
抹茶落季
抹茶落季 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: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) )

提交回复
热议问题