C# 在一个带括号的标记之后,如何解析所有值

C# 在一个带括号的标记之后,如何解析所有值,c#,text-parsing,C#,Text Parsing,我有一个如下结构的文本文件 [email] emailAddress emailAddress emailAddress [somthingelse] stuff stuff stuff 等等 我尝试了几种正则表达式、文件读取和流读取器方法,但都没有成功 我需要将每个[xxxx]下的所有值放入列表中 例如: List email=newlist(); 在文件中搜索[email]将电子邮件地址添加到列表中。 继续阅读下一篇[smothingelse]将值添加到“其他内容”列表中 等等 有什么

我有一个如下结构的文本文件

[email]
emailAddress
emailAddress
emailAddress

[somthingelse]
stuff
stuff
stuff
等等

我尝试了几种正则表达式、文件读取和流读取器方法,但都没有成功

我需要将每个
[xxxx]
下的所有值放入列表中 例如:

List email=newlist();
在文件中搜索
[email]
将电子邮件地址添加到列表中。 继续阅读下一篇
[smothingelse]
将值添加到“其他内容”列表中

等等


有什么帮助吗?

它看起来像.ini文件。有很多c#库可用于解析这一点。但假设你想按自己的方式做:

foreach line in file:

    if line contains "[email]":
        _list_you_need  is "Email list"
        continue

    _list_you_need.push(line)
与林克

        var emailList = File.ReadLines(inputFile)
                        .SkipWhile(x => x != "[email]")
                        .Skip(1)
                        .TakeWhile(x => !x.StartsWith("["))
                        .Where(x=>!string.IsNullOrEmpty(x))
                        .ToList();
以下是您的解决方案:

Dictionary<string,List<string>> values = new Dictionary<string, List<string>>();

var lines = File.ReadAllLines("file.txt");
var reg = new Regex(@"^\[(\w+)\]$", RegexOptions.Compiled);
string lastMatch = "";

foreach (var ligne in lines.Where(a=>!String.IsNullOrEmpty(a)))
{
    var isMatch =  reg.Match(ligne);
    if (isMatch.Success)
    {
        lastMatch = isMatch.Groups[0].Value;
        if(!values.ContainsKey(lastMatch))
            values.Add(lastMatch,new List<string>());
    }else
        values[lastMatch].Add(ligne);
}
字典值=新字典();
var lines=File.ReadAllLines(“File.txt”);
var reg=new Regex(@“^\[(\w+)\]$”,RegexOptions.Compiled);
字符串lastMatch=“”;
foreach(行中的var ligne.Where(a=>!String.IsNullOrEmpty(a)))
{
var isMatch=reg.Match(对齐);
if(isMatch.Success)
{
lastMatch=isMatch.Groups[0]。值;
如果(!values.ContainsKey(lastMatch))
Add(lastMatch,newlist());
}否则
值[lastMatch]。添加(对齐);
}
它将为您提供一个字典,其中包含每个标记的所有值,并转义空行。您的文件必须以您提到的标记开头。 Regex只是检测[]的存在并捕获内容。它将与标签关联标签后面的所有元素。直到找到另一个标签


当然,正如您所看到的,预期的结果包含在values变量中。

到目前为止您写了什么?只要在每一行中循环,如果它是[xxxx],您知道您将要开始将后续行分配给特定集合。重复如果你想要一个更详细的答案,你需要发布一个更详细的问题。即使是伪代码,这也是不正确的。至少,你可以解释一下为什么OP可以理解它甚至不是C!?用户未显示任何代码片段。我给了他一些伪代码。不是他想要的实际解决方案。
用户没有显示任何代码片段
然后询问他
不是他想要的实际解决方案。
所以你自己承认这不是答案。深呼吸,这是有史以来最长的句子。
SkipWhile(x=>x==“[电子邮件]”)
是不正确的,只有在第一行时才有效。我纠正了。谢谢你,这正是我想要的。我没想过在这个庄园里用字典。
Dictionary<string,List<string>> values = new Dictionary<string, List<string>>();

var lines = File.ReadAllLines("file.txt");
var reg = new Regex(@"^\[(\w+)\]$", RegexOptions.Compiled);
string lastMatch = "";

foreach (var ligne in lines.Where(a=>!String.IsNullOrEmpty(a)))
{
    var isMatch =  reg.Match(ligne);
    if (isMatch.Success)
    {
        lastMatch = isMatch.Groups[0].Value;
        if(!values.ContainsKey(lastMatch))
            values.Add(lastMatch,new List<string>());
    }else
        values[lastMatch].Add(ligne);
}