简体   繁体   English

从结构为“key = value”的字符串中解析值

[英]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. 现在我需要从这个字符串中获取RCV_VALUE和RESULT的值。 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 . RESULT的值我必须得到int ,RCV_VALUE的值必须得到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. 在此之后我会使用indexof和substring或string remove来获取我想要的部分。

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. 我建议你去www.codeproject.com学习基础知识。

尝试

var RCV_VALUE = Regex.Match(myString, "RCV_VALUE=(\d+)").Groups[1].Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM