0

可以说我有这样的类定义(相当简单):

class Person
{
  public string Balance;
  public string Escrow;
  public string Acc;
  // .. and more 

}

我需要将此字符串解析为上面的类:

BALANCE:      746.67     ESCROW PAYMENT:      271.22     LAST ACT:05/03/12
ACC: 10                   YTD DIVIDENDS:          .27   ENTRY DATE:12/20/10

字符串以这种奇怪的格式出现。

我正在考虑逐行阅读并解析其内容,但我可能喜欢学习更好的方法。至少2个大脑比1个大脑强。

4

2 回答 2

1

如果字符串始终采用该格式,那么您应该能够仅拆分“:”字符并索引到数组中。

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]
  };
}
于 2012-05-31T18:58:18.417 回答
1

您可以使用正则表达式从源字符串中提取每个属性的值,如下所示:

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

正则表达式方法非常灵活,因为即使属性的顺序或空格的数量发生了变化,它也可以工作。

于 2012-05-31T20:21:02.797 回答