你可以使用一個regular expression提取值每個屬性從源字符串,像這樣:
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
正則表達式的方法是相當靈活的,因爲它會即使性質或空格數量的順序改變工作。
您需要能夠區分標題(屬性名稱)中的數據。有沒有什麼規則可以用來做到這一點?標題總是至少有兩個空格嗎?或者,你可以假設標題字符串總是完全一樣嗎? – phoog