我有一个字符串看起来像这样:
/Gender=&Age=&Query=&Orgrimmar+l%C3%A4n=01&Stormwind+l%C3%A4n=07&Undercity+l%C3%A4n=09&Pag
我想要一个字符串列表" Orgrimmar"," Stormwind"和"幽暗城"。这怎么可能,以便它在查询之后和之间分开。和+为了避免得到像这样的字符串"奥格瑞玛+ l%C3%A4n = 01&暴风城"。
我们假设我们不知道字符串的名称.. :)
更新了,我似乎还没有让它发挥作用。我添加了一个可用于验证这一点的县列表。但是在这种情况下我仍然觉得很难。 countyList用于验证url中的县/城市是否与预先存在的Collection匹配。
var countyQuery = Request.Url.Query;
var counties = this._locationService.GetAllCounties();
List<string> countyList = new List<string>();
List<string> selectedCountiesList = new List<string>();
foreach (var i in counties)
{
countyList.Add(i.Name);
}
Regex r = new Regex(@"&(.+?)\+");
MatchCollection mc = r.Matches(countyQuery);
foreach (Match curMatch in mc)
{
if (countyList.Contains(curMatch.Groups[1].Value))
{
selectedCountiesList.Add(curMatch.Groups[1].Value);
}
}
return selectedCountiesList;
更改网址为/?性别=&amp;年龄=&amp;查询=&amp; county = 13&amp; county = 08&amp; county = 01&amp; Page = 1 其中13,08,01等是县的Id 最终的解决方案是: var selectedCountyQuery = Request.QueryString // CountySearch =&#34; county&#34; [QueryStringParameters.CountySearch]; 列出countyList = new List();
List<string> selectedCounties = new List<string>();
if (!string.IsNullOrEmpty(selectedCountyQuery))
{
var selectedCountiesArray = selectedCountyQuery.Split(new[]{ ',' });
foreach (var selectedCounty in selectedCountiesArray)
{
selectedCounties.Add(selectedCounty);
}
}
return selectedCounties;
答案 0 :(得分:0)
您可以使用Substring()
和Split()
方法获取所有参数和值。
示例:
var URL = "controller/method?var1=&var2=&var3=dsgdf";
var ParameterPart = URL.Split("?")[1];
var ParametersArray = ParameterPart.Split("&");
//output : ["var1=","var2=","var3=dsgdf"];
foreach(var Parameter in ParametersArray)
{
var ParameterName= Parameter.Split("=")[0];
var ParameterValue= Parameter.Split("=")[1];
}
答案 1 :(得分:0)
您可以使用正则表达式并提取匹配项:
Regex r = new Regex(@"&(.+?)\+");
MatchCollection mc = r.Matches(s);
然后你可以把你想要的字符串(在这种情况下是哇城市)改为:
foreach(Match curMatch in mc)
{
Console.WriteLine(curMatch.Groups[1].Value);
}
答案 2 :(得分:0)
string[] numbers ={ "/Gender=&Age=&Query=&Orgrimmar+l%C3%A4n=01&Stormwind+l%C3%A4n=07&Undercity+l%C3%A4n=09&Pag"};
string sPattern = @"(?<=&Orgrimmar)+";
foreach (string s in numbers){
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern)){
System.Console.WriteLine(" - valid");}
else{System.Console.WriteLine(" - invalid");}
输出:有效
string[] numbers ={ "/Gender=&Age=&Query=Orgrimmar+l%C3%A4n=01&Stormwind+l%C3%A4n=07&Undercity+l%C3%A4n=09&Pag"};
输出:无效
进一步检查两个参数:
string[] numbers ={ "/Gender=&Age=&Query=&Orgrimmar+l%C3%A4n=01&Stormwind+l%C3%A4n=07&Undercity+l%C3%A4n=09&Pag"};
string sPattern = @"(?<=&Orgrimmar)+";
string sPattern2 = @"(?<=&Stormwind)+";
foreach (string s in numbers){
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern) && System.Text.RegularExpressions.Regex.IsMatch(s, sPattern2))
...