简体   繁体   中英

Extract Value from String

What is the best way to read RESULT from this string ? Only string needs to be parsed, it's returned from web service

"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.

You could use LINQ to build a dictionary:

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 .

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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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