简体   繁体   English

从字符串中提取值

[英]Extract Value from String

What is the best way to read RESULT from this string ? 从此string读取RESULT的最佳方法是什么? Only string needs to be parsed, it's returned from web service 仅字符串需要解析,它是从Web服务返回的

"RESULT: FAILED
 RESULT_CODE: 944
 RRN: 313434415392
 APPROVAL_CODE: 244447
 CARD_NUMBER: 4***********3412";

I can user mystring.split(' ') , but it's not good idea i think. 我可以使用mystring.split(' ') ,但是我认为这不是一个好主意。

You could use LINQ to build a dictionary: 您可以使用LINQ来构建字典:

string s = 
    @"RESULT: FAILED
    RESULT_CODE: 944
    RRN: 313434415392
    APPROVAL_CODE: 244447
    CARD_NUMBER: 4***********3412";

IDictionary<string, string> result = s
    .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Select(line => line.Split(':'))
    .ToDictionary(x => x[0].Trim(), x => x[1].Trim());

and then query the results by key: 然后按键查询结果:

Console.WriteLine(result["RRN"]);

would give you 313434415392 . 会给你313434415392

Or if you wanted to get all keys and values simply loop: 或者,如果您想获取所有键和值,只需循环:

foreach (var item in result)
{
    Console.WriteLine("key: {0}, value: {1}", item.Key, item.Value);
}
string text = @"RESULT: FAILED
 RESULT_CODE: 944
 RRN: 313434415392
 APPROVAL_CODE: 244447
 CARD_NUMBER: 4***********3412";

using (StringReader reader = new StringReader(text))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        var values = line.Split(':');
        if (values.Length > 1 && values[0].Trim() =="RESULT")
        {
            var found = values[1].Trim(); // this is the value you want 
            break;
        }
    }
}

您可以使用split(“ \\ n”)吗?

var regex = new Regex(@"(RESULT:)[a-zA-Z0-9\t .]+");
string text = @"RESULT: FAILED
 RESULT_CODE: 944
 RRN: 313434415392
 APPROVAL_CODE: 244447
 CARD_NUMBER: 4***********3412";

MatchCollection matches = regex.Matches(text);

foreach (Match m in matches)
{
    string values = m.Value;
}

I'm not sure if you are trying to avoid the loop, perhaps your dataset is fairly large. 我不确定是否要避免循环,也许您的数据集相当大。 An alternative to the solutions being offered here, would be to find your match with a regular expression. 此处提供的解决方案的替代方法是使用正则表达式查找匹配项。 I'm sure you could come up with the perfect regex to match your dataset, but this one should be good matching on RESULT to end of line containing letters and numbers, although I believe it would need to be tweaked for special characters if they were contained in your dataset. 我敢肯定,您会想出一个完美的正则表达式来匹配您的数据集,但是此结果在RESULT上应该可以很好地匹配包含字母和数字的行尾,尽管我认为如果需要特殊字符,则需要对其进行调整包含在您的数据集中。 Below should give you an idea of what I mean; 下面应该让您了解我的意思;

Create an entity (class) and return its instance. 创建一个实体(类)并返回其实例。

public class ReturnValues
{
    public string Result {get; set;}
    public string return_Code
    // Other properties
}

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

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