extract query string from a URL string

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

提交回复
热议问题