且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从URL字符串中提取查询字符串

更新时间:2022-04-02 22:38:18

目前尚不清楚为什么您不想使用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));