Pavel F Pavel F - 1 month ago 7
C# Question

Parse value from string with structure "key=value"

I have a string like this:

SUBJECT=Some text here\r\n
VALUE=19355711\r\n
RCV_VALUE=2851404175\r\n
RESULT=1\r\n
CNCODE=0\r\n
KEY1=1\r\n
KEY2=2


Now I need to get the values of RCV_VALUE and RESULT from this string. The position of these keys in the string may vary. They can also be at the beginning or/and at the end of the string.

Value of RESULT I must get as
int
, and value of RCV_VALUE I must get as
string
.

What is the best way to get the values of these keys regardless of their position in the string?

Answer

Best bet is a regular expression

var regex=new Regex(@"RCV_VALUE=(?<value>\d+)");
var match=regex.Match(inputString);
var rcv_value=int.Parse(match.Groups["value"].Value);