c#在循环中向List中添加Array元素

本文关键字:添加 Array 元素 List 循环 | 更新日期: 2023-09-27 18:08:17

我的代码应该接受一个多行输入字符串,然后将该字符串的元素添加到一个新的List中。

一个示例输入看起来像这样:

[ (Nucleosome, Stable, 21, 25), (Transcription_Factor, REB1, 48, 6), (Nucleosome, Stable, 64, 25), (Transcription_Factor, TBP, 90, 5) ]
[ (Transcription_Factor, MCM1, 2, 8), (Nucleosome, Stable, 21, 25), (Transcription_Factor, REB1, 48, 6), (Nucleosome, Stable, 64, 25) ] 

我希望我的代码将返回一个单独的行列表,包括所有的元素。但是,我当前的输出只捕获每行的第一个元素。像这样:

Found type: 'Nucleosome', Found subtype: 'Stable', Found position: '21', Found length '25'
Found type: 'Transcription_Factor', Found subtype: 'MCM1', Found position: '2', Found length '8'

理想的输出是这样的:

Found type: 'Nucleosome', Found subtype: 'Stable', Found position: '21', Found length '25'
Found type: 'Transcription_Factor', Found subtype: 'REB1', Found position: '48', Found length '6'
Found type: 'Nucleosome', Found subtype: 'Stable', Found position: '64', Found length '25'
Found type: 'Transcription_Factor', Found subtype: 'TBP', Found position: '90', Found length '5'

下面是我当前的代码:

public static void read_time_step(string input)
{
    string pattern = @"'(((.*?))')";
    string intermediateString1 = "";
    string[] IntermediateArray = (intermediateString1).Split (new Char[] {' '});
    List<string> IntermediateList;
    IntermediateList = new List<string> ();
    foreach(Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
        {
            intermediateString1 = Regex.Replace(match.Value, "[.,()]?", "");
            IntermediateArray = (intermediateString1).Split (new Char[] {' '});
            IntermediateList.AddRange (IntermediateArray);
        }
    Console.WriteLine("Found type: '{0}', Found subtype: '{1}', Found position: '{2}', Found length '{3}'", IntermediateList[0], IntermediateList[1], IntermediateList[2], IntermediateList[3]);

有没有人有任何建议,我如何才能解决这个问题,并使它输出我想要的?

c#在循环中向List中添加Array元素

这是一个经典的非贪婪正则表达式。有很多方法可以做到这一点(也许更好),但以下方法可以完成您的工作(注意模式的非贪婪语法):

    static void Main(string[] args)
    {
        string input = "[ (Nucleosome, Stable, 21, 25), (Transcription_Factor, REB1, 48, 6), (Nucleosome, Stable, 64, 25), (Transcription_Factor, TBP, 90, 5) ]";
        read_time_step(input);
        Console.Read();
    }
    public static void read_time_step(string input)
    {
        string pattern = @"'((.)*?')";
        MatchCollection mc = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
        foreach (Match match in mc)
        {
            string v = match.Value.Trim('(', ')');
            string[] IntermediateList = v.Split(',');
            Console.WriteLine("Found type: '{0}', Found subtype: '{1}', Found position: '{2}', Found length '{3}'", 
            IntermediateList[0].Trim(), IntermediateList[1].Trim(), IntermediateList[2].Trim(), IntermediateList[3].Trim());
        }
    }