c# Fastest way to get values from string [closed]

I have a C# app that receives the following commands, via tcp sockets.

{
key = "foo",
value = 1.6557,
}


I'm currently using this method to get the key-value pairs and store them to a classes auto properties.

private Regex _keyRegex = new Regex("\"(.)*\"");
private Regex _valueRegex = new Regex(@"\d*\.{1}\d*");

private MyClass CrappyFunction(string nomnom)
{
// Gets a match for the key
var key = _keyRegex.Match(nomnom);
// Gets a match for the value
var value = _valueRegex.Match(nomnom);
// Tests if got matches for both. If not, returns null.
if (!key.Success || !value.Success) return null;
// Found both values, so it creates a new MyClass and returns it
// Also removes the " chars from the key
return new MyClass(
key.ToString().Replace("\"", string.Empty),
value.ToString());
}


Even though it works, I have a really bad feeling looking at this particular piece of code. It's ugly, in the sense that I'm using two regex objects to achieve my goal. Any suggestions will be appreciated.

closed as off-topic by Jamal♦Mar 31 at 1:17

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Jamal
If this question can be reworded to fit the rules in the help center, please edit the question.

• Is json comming in over the sockets, because there are libraries to parse that. – pacmaninbw Mar 30 at 23:08

2 Answers

If you don't want to use a JSON library, you can combine the 2 regex expressions into one and use named groups (?<name>expression).

private static Regex _regex =
new Regex(@"""(?<key>.*)"".*?(?<value>\d*\.\d*)", RegexOptions.Compiled);


The you get the result with

var match = _regex.Match("{ key = \"foo\", value = 1.6557, }");
string key = match.Groups["key"].Value;
string value = match.Groups["value"].Value;


Note that in a verbatim string, double quotes must be escaped by doubling them. The named group key does not include the double quotes, so you get the key directly.

So I basically have the regex

key_expression.*?value_expression


Both expressions are separated by .*?. The quotation mark tells the * to be lazy, i.e. to take as few characters as possible. If you don't, it will swallow the digits before the decimal point.

May not be the fastest but using 'LINQ' and 'split' it is easy to extract out the values.

var keyValue =
data
.Split(',')
.Select(
part => part.Split('='))
.Take(2)
.Select(
parts => parts[1].Trim())
.ToArray();

var key = keyValue[0].Replace("\"", string.Empty);
var value = keyValue[1];


First split is on the ','
The results of that is split on '='.
Take(2), ignores the 3rd part of the first split.