levi
levi

Reputation: 3511

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.

Upvotes: 1

Views: 162

Answers (5)

clamchoda
clamchoda

Reputation: 4941

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;

Upvotes: 1

Damith
Damith

Reputation: 63065

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

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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);
}

Upvotes: 5

Virus
Virus

Reputation: 167

Could you use split("\n")?

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Create an entity (class) and return its instance.

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

Upvotes: 0

Related Questions