我的字符串变量有这样的值
string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
当我从XML中提取时Endpoint
,Intervene
,Mask
和Purpose
仍然存在
同样但它的价值可以改变。
我想将此Endpoint
,intervene
,mask
和purpose
分别存储在不同的变量中,我们将非常感谢您的帮助。
答案 0 :(得分:1)
使用Dictionary
string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
Dictionary<string, string> result = new Dictionary<string, string>();
var s1 = hello.Split(',');
foreach (var s in s1)
{
var v = s.Split(':');
result.Add(v[0].Trim(), v[1].Trim());
}
之后,您可以使用key
value
Dictionary
获得结果
foreach (var a in result)
{
Console.WriteLine(a.Key +" " + a.Value);
}
答案 1 :(得分:1)
var result = hello.Split(',')
.Select(part => part.Split(':'))
.ToDictionary(split => split[0], split => split[1].Trim());
答案 2 :(得分:0)
如果模式已修复,这可以帮助您。
string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
string[] packs = hello.Split(',');
var data = packs.ToDictionary(k => k.Split(':').First().Trim(), v => v.Split(':').Last().Trim());
答案 3 :(得分:0)
首先将string
分割为,
,然后再分类为:
并将结果保存在字典中:
public class Program
{
public static void Main(string[] args)
{
string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
string[] arr = hello.Split(',');
Dictionary<string, string> result = new Dictionary<string, string>();
foreach(string s in arr)
{
string[] keyValuePair = s.Split(':');
result[keyValuePair[0].Replace(" ","")] = keyValuePair[1].Replace(" ","");
}
foreach(var v in result)
{
Console.WriteLine(v.Key + " : " + v.Value );
}
}
}
答案 4 :(得分:0)
我想出了一些更有活力的东西,万一有人必须处理变量关键字才能匹配。
首先提取关键字并构建匹配的模式。然后按名称捕获匹配项,每个捕获组以关键字命名,以便我们可以通过关键字访问它们:
var input = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
//extract keywords: (word followed by ':' )
var keywords = Regex.Matches( input, @"(\w*):" ).Cast<Match>()
.Select( m => m.Groups[ 1 ].Value );
//build the pattern to match (create capture groups named as keywords)
var pattern = String.Join( ", ", keywords.Select(
k => k + $@": (?<{k}>(\w*\s*)*)" ) );
var matches = Regex.Matches( input, pattern );
//access groups by keyword
foreach( var keyword in keywords )
Console.WriteLine( matches[ 0 ].Groups[ keyword ].Value );