Hi @Markus Freitag , Welcome to Microsoft Q&A,
The (?<=(^|\^))
inside the regex pattern is a positive lookbehind assertion. It asserts that what precedes the current position in the string is either the start of the string ^
or a ^
character.
Now I would like to have a dictionary that contains the group names
string[] inputs ={
"Object0-EAN13CODE^27730180^Object1-TEXT^104612^Object2-TEXT^27730180^Object3-TEXT^AT1^",
"Object0-EAN13CODE^27730181^Object1-TEXT^104612^Object2-TEXT^27730181^Object3-TEXT^AT1^",
"Object0-EAN13CODE^27730182^Object1-TEXT^104612^Object2-TEXT^27730182^Object3-TEXT^AT1^",
};
// Define a simpler regex pattern
Regex reg = new Regex(@"Object(?<NUM>\d+)-(?<KEY>.+?)\^(?<VALUE>.*?)\^");
var dictionaries = new List<Dictionary<int, object>>();
foreach (string input in inputs)
{
// Match all key-value pairs in the input string
MatchCollection matches = reg.Matches(input);
// Create a dictionary to hold the key-value pairs for this input
Dictionary<int, object> dict = new Dictionary<int, object>();
// Iterate over each match and add it to the dictionary
foreach (Match match in matches)
{
int num = int.Parse(match.Groups["NUM"].Value);
string key = match.Groups["KEY"].Value;
string value = match.Groups["VALUE"].Value;
// Store key-value pairs in the dictionary
dict[num] = new { type = key, value = value };
}
// Add the dictionary for this input to the list of dictionaries
dictionaries.Add(dict);
}
// Output the dictionaries
for (int i = 0; i < dictionaries.Count; i++)
{
Console.WriteLine($"Dictionary {i + 1}:");
foreach (var kvp in dictionaries[i])
{
Console.WriteLine($" Key: Object{kvp.Key}, Value: type={kvp.Value.GetType().GetProperty("type").GetValue(kvp.Value)}, value={kvp.Value.GetType().GetProperty("value").GetValue(kvp.Value)}");
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.