Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract query string from a URL string

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

like image 877
michelle Avatar asked May 21 '11 15:05

michelle


2 Answers

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));
like image 181
Ahmad Mageed Avatar answered Oct 24 '22 18:10

Ahmad Mageed


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.

like image 24
Teoman Soygul Avatar answered Oct 24 '22 18:10

Teoman Soygul