从许多行解析行组(Parsing group of rows from many rows)

编程入门 行业动态 更新时间:2024-10-23 07:33:31
从许多行解析行组(Parsing group of rows from many rows)

我试图解析字符串[]中的一组行,如下所示:

垃圾...... 标题先生..... < - 开始相关数据 别名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; } }

更多推荐

本文发布于:2023-08-07 19:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Parsing   group   rows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!