我怎样才能在特定的制动标签后按下所有值

How can I go about Parsing all values after a specfic bracked tag

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

[email]
emailAddress
emailAddress
emailAddress

[somthingelse]
stuff
stuff
stuff

等...

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

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

List<string> email = new List<string>();

搜索 [email] 的文件,将电子邮件地址添加到列表中。 继续阅读下一个 [smothingelse] 将值添加到其他列表

等...

请帮忙

好像是.ini文件。有很多 c# 库可以解析它。但假设您想按自己的方式行事:

foreach line in file:

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

    _list_you_need.push(line)

使用 Linq

        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);
}

它会给你一个字典,其中包含每个标签的所有值,转义空行,你的文件必须以你提到的标签开头。 正则表达式只是检测 [] 存在并捕获内容。它将把标签后面的所有元素关联到标签。直到找到另一个标签。

当然,如您所见,预期结果包含在 values 变量中。