我试图解析字符串[]中的一组行,如下所示:
垃圾...... 标题先生..... < - 开始相关数据 别名johnsmith ... 别名john.smith ... 称呼...... < - 结束相关数据 垃圾...... 垃圾...... 标题太太..... < - 开始相关数据 别名janesmith ... 别名jane.smith ... 称呼...... < - 结束相关数据 垃圾......我需要提取每组记录的信息......如下所示:
User.Title User.alias User.alias User.Salutation
我一直试图弄清楚如何最好地处理这个,比如使用正则表达式或分层循环,但似乎无法理解这一点。 有没有人以前处理过此问题并提出一些建议?
I am trying to parse a group of lines in a string[] that looks like the following:
junk .... Title Mr ..... <-- begin relevant data alias johnsmith... alias john.smith... Salutation ... <-- end relevant data junk ... junk .... Title Mrs ..... <-- begin relevant data alias janesmith... alias jane.smith... Salutation ... <-- end relevant data junk ...I need to extract the info for each group of records... something like the following:
User.Title User.alias User.alias User.Salutation
I have been trying to figure out how best to handle this, like using a Regex or layered looping, but can't seem to get my head around this. Has anyone dealt with this before and could provide some suggestions?
最满意答案
当Title出现时,您可以只foreach行并开始记录数据,直到出现Salutation 。
就像是:
var lines = File.ReadLines("c:\\StackOverflow.txt"); List<User> results = new List<User>(); bool titleFound = false; User current = null; foreach (var line in lines) { if (line.StartsWith("Title")) { titleFound = true; current = new User { Alias = new List<string>() }; current.Title = line; } if (titleFound) { if (line.StartsWith("alias")) { current.Alias.Add(line); } if (line.StartsWith("Salutation")) { current.Salutation = line; results.Add(current); titleFound = false; } } } public class User { public string Title { get; set; } public List<string> Alias { get; set; } public string Salutation { get; set; } }You could just foreach the lines and start recording data when Title appears untill Salutation appears.
Something like:
var lines = File.ReadLines("c:\\StackOverflow.txt"); List<User> results = new List<User>(); bool titleFound = false; User current = null; foreach (var line in lines) { if (line.StartsWith("Title")) { titleFound = true; current = new User { Alias = new List<string>() }; current.Title = line; } if (titleFound) { if (line.StartsWith("alias")) { current.Alias.Add(line); } if (line.StartsWith("Salutation")) { current.Salutation = line; results.Add(current); titleFound = false; } } } public class User { public string Title { get; set; } public List<string> Alias { get; set; } public string Salutation { get; set; } }更多推荐
发布评论