我的代码应该接受包含多行的输入字符串,然后将该字符串的元素添加到新的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) ]
我希望我的代码会为单个行返回一个List,其中包含所有元素。 但是,我当前的输出只捕获每行的第一个元素。 像这样:
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]);
有没有人对我如何解决这个问题有任何建议,并让它输出我想要的内容?
答案 0 :(得分:0)
这是一款经典的非贪婪RegEx。有很多方法可以做到(也许更好),但以下将完成你的工作(注意模式的非贪婪语法):
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());
}
}