从URL字符串中提取查询字符串 [英] extract query string from a URL string
问题描述
我正在阅读历史记录,我希望当我遇到Google查询时,我可以提取查询字符串.我不使用请求或httputility,因为我只是解析一个字符串.但是,当我遇到这样的URL时,我的程序无法正确解析它:
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:
我想做的是获取q =的索引和&的索引.并使用介于两者之间的单词,但在这种情况下,索引为&会小于q =,这会给我错误.
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.
有什么建议吗?
感谢您的回答,一切似乎都很好:) p.s.我不能使用httputility,不是我不想.当我添加对system.web的引用时,不包括httputility!它仅包含在asp.net应用程序中.再次感谢
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
推荐答案
目前尚不清楚为什么您不想使用HttpUtility.您始终可以添加对 System.Web
的引用并使用它:
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);
它将在&
上拆分并查找以"q ="
开头的单个拆分结果,并采用位置2的子字符串返回之后的所有内容> =
符号.假设只有一个匹配项,在这种情况下似乎是合理的,否则将引发异常.如果不是这种情况,则将 Single
替换为 Where
,在结果中循环并在循环中执行相同的子字符串操作.
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.
编辑:以覆盖此注释可以使用的更新版本:
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));
这篇关于从URL字符串中提取查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!