您可以使用正则表达式从源字符串中提取每个属性的值,如下所示:
using System.Text.RegularExpressions;
...
Regex balanceRegex = new Regex("(?<=BALANCE:\\s*)[^\\s]+");
string balance = balanceRegex.Match(source).Value;
这可以包含在一个函数中以搜索任何命名属性,如下所示:
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;
}
然后你可以像这样填充一个 Person 对象:
Person person = new Person
{
Balance = GetProperty(source, "Balance"),
Escrow = GetProperty(source, "Escrow Payment"),
Acc = GetProperty(source, "Acc")
};
例如,如果您的属性值中有空格,您可能需要调整正则表达式,例如ACCOUNT NAME: MR SMITH
正则表达式方法非常灵活,因为即使属性的顺序或空格的数量发生了变化,它也可以工作。