Reputation: 81711
Lets say I have class definition like this (fairly simple):
class Person
{
public string Balance;
public string Escrow;
public string Acc;
// .. and more
}
and I need to parse this string into the class above:
BALANCE: 746.67 ESCROW PAYMENT: 271.22 LAST ACT:05/03/12
ACC: 10 YTD DIVIDENDS: .27 ENTRY DATE:12/20/10
The string comes in this weird format.
I am thinking to read each line one by one and parse its content but I like to learn a better way maybe. At least 2 brains are stronger than one brain.
Upvotes: 0
Views: 2056
Reputation: 707
You could use a regular expression to extract the value for each property from the source string like so:
using System.Text.RegularExpressions;
...
Regex balanceRegex = new Regex("(?<=BALANCE:\\s*)[^\\s]+");
string balance = balanceRegex.Match(source).Value;
This could be wrapped up in a function to search for any named property like this:
private static string GetProperty(string source, string propertyName)
{
string pattern = String.Format("(?<={0}:\\s*)[^\\s]+", propertyName);
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.Match(source).Value;
}
Then you could populate a Person object like this:
Person person = new Person
{
Balance = GetProperty(source, "Balance"),
Escrow = GetProperty(source, "Escrow Payment"),
Acc = GetProperty(source, "Acc")
};
You might need to tweak the regex if, for example, you have whitespace inside your property values e.g. ACCOUNT NAME: MR SMITH
The regex approach is quite flexible as it will work even if the order of the properties or the amount of whitespace changed.
Upvotes: 1
Reputation: 754595
If the string is always in that format then you should be able to just split on a ":" character and index into the array.
public Person ParsePerson(string line1, string line2)
{
string[] fields1 = line1.Split(new char[] {':', ' '}, StringSplitOptions.RemoveEmptyEntries);
string[] fields2 = line2.Split(new char[] {':', ' '}, StringSplitOptions.RemoveEmptyEntries);
return new Person() {
Balance = fields1[1],
Escrow = fields1[3],
Acc = fields1[1]
};
}
Upvotes: 1