gpt4 book ai didi

C# 在循环中将数组的元素添加到列表

转载 作者:行者123 更新时间:2023-11-30 12:59:42 27 4
gpt4 key购买 nike

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

示例输入如下所示:

[ (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]);

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

最佳答案

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

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

关于C# 在循环中将数组的元素添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24190395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com