Kevin Appleyard
Kevin Appleyard

Reputation: 149

Dotnet Extracting values from string

I need to be able to extract values from a string like the one below, and assign them to specific variables.

[1;1HSVC_LVL={89} CALLS_OFF={966} CALLS_Q={2} CURR_DEL={67}[K[2;1HACD_HOLD={4} AN_WAIT={3} NRDY_WRAP={9} WALK_AWAY={14} FRCD_OFF={12}[K[4;1H{EOM}[K

The actual string is somewhat longer, and contains about 16 key/value pairs. It can also contain extraneous characters as shown above. This string will be arriving every few seconds, and I need to parse the values out to variables fairly quickly each time. I'll have a seperate variable for each key/value pair.

Within the string, I need to search for the key name, ie 'SVC_LVL' and assign the key value (contained within '{}' ie '89' for key name 'SVC_LVL') to a variable. The values will not necessarily be the same length each time, so I cant simply strip a specific number of chars from the string, need to pull the value within '{}'

So what I'm really looking for is a way to find each specific key name (which I do know in advance), then pull the value from within the next '{}' after it, assign that to a value, and proceed to the next one.

Not sure if regex is the best way to be doing that, and what would be an example for pulling each one out seperately. Is doing that 16 times a sensible thing? or should I be looking at a different way?

Thanks for any help

Upvotes: 0

Views: 162

Answers (1)

Sina Iravanian
Sina Iravanian

Reputation: 16296

Use this if you want to search for a specific key:

string key = "SVC_LVL";
string pattern = key + @"\=\{(?<value>[^\}]+)\}";
foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine(m.Groups["value"].Value);
}

Or use this to list all key-value pairs:

string patAllKeyValues = @"(?<key>[\p{L}_]+)\=\{(?<value>[^\}]+)\}";
foreach (Match m in Regex.Matches(input, patAllKeyValues))
{
    Console.WriteLine("{0} -> {1}", 
                       m.Groups["key"].Value, 
                       m.Groups["value"].Value);
}

Upvotes: 3

Related Questions