简体   繁体   English

从字符串中提取子字符串

[英]Extract substrings from a string

I have string variable that has value like this 我有一个具有这样的值的字符串变量

string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";

As I am extracting from XML so Endpoint , Intervene , Mask and Purpose remains same but its value can change. 正如我从XML中提取的那样, EndpointInterveneMaskPurpose保持不变,但其值可以更改。 I want to store this Endpoint , intervene , mask and purpose separately in different variables any help will be much appreciated. 我想将此Endpointintervenemaskpurpose分别存储在不同的变量中,任何帮助将不胜感激。

Try this way using Dictionary 使用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());
        }

After that you can get result using key value of the Dictionary 之后,你可以得到使用结果key value的的Dictionary

        foreach (var a in result)
        {
            Console.WriteLine(a.Key +" " + a.Value);
        }
var result = hello.Split(',')
               .Select(part => part.Split(':'))
               .ToDictionary(split => split[0], split => split[1].Trim());

If the pattern is fixed, this can help you. 如果该模式是固定的,则可以为您提供帮助。

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());

Split your string first by , and then by : and save the result in dictionary: 首先用,然后用:分割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 );
        }


    }
}

I came up with something more dynamic just in case someone have to deal with variable keywords to match. 我想出了一些更动态的方法,以防万一有人不得不处理可变关键字以进行匹配。

This first extracts the keywords and builds a pattern to match. 首先提取关键词并建立匹配模式。 Matches are then captured by name and each capture group is named after a keyword so that we can access them by keyword: 然后按名称捕获匹配项,每个捕获组均以一个关键字命名,以便我们可以通过关键字进行访问:

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM