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=285140417开发者_JAVA技巧5\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?
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);
You can achieve this using an regular expression easily enough, as per the example below.
Regex expr = new Regex(@"^(?<Key>.*)=(?<Value>.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var m = expr.Match("SUBJECT=Some text here\r\n");
var key = m.Groups["Key"].Value;
var value = m.Groups["Value"].Value;
// or
var kvp = new KeyValuePair<string, string>(m.Groups["Key"].Value, m.Groups["Value"].Value);
Or alternatively if you do not want to use a regular expression you can split the string using the =
as a delimiter and then parse the values in pairs.
Use string spilt to split it into multiple lines, and then loop over the array. After this i would use indexof and either substring or string remove to get the parts i want.
This all being said, this questions smells of "do my work for me". I would recommend going to www.codeproject.com and learn the basics.
Try
var RCV_VALUE = Regex.Match(myString, "RCV_VALUE=(\d+)").Groups[1].Value
精彩评论