DNA加密突变过程:寻找子串

时间:2018-05-24 03:04:51

标签: c# regex

我有这个氨基酸序列:PhePheLeoArgStopValGlyArgTyrStopPheArgGleHis

我想在这个序列上应用一个突变点,以便结果将是从上面的序列生成的一些键,如下所示:

key1:PhePheLeoArgStopValGlyArgTyrStopPheArgGleHis
key2:ValGlyArgTyrStopPheArgGleHis
key3:PheArgGleHis

因此,当它到达Stop时,它会创建一个由字符串其余部分组成的密钥。

我尝试了以下代码,但没有按预期工作:

string mRNA = textBox3.Text;
string Rna = mRNA.Replace("Stop", "*");
string[] keys = Rna.Split('*');
foreach (string key in keys)
{
    listBox1.Items.Add( key);
}

任何人都可以帮我修理代码吗?

3 个答案:

答案 0 :(得分:3)

我会使用indexOf解决方案来解决这个问题。见下文:

 var rna = "PhePheLeoArgStopValGlyArgTyrStopPheArgGleHis";
 var keys = new List<string>();
 var pos = -1;

 //prime the loop by adding the first item           
 keys.Add(rna);
 listBox1.Items.Add(keys.Last());

 //loop through all the occurrecnces of "Stop" and add they key
 while ((pos = rna.IndexOf("Stop", pos + 1)) >= 0)
 {
     keys.Add(rna.Substring(pos+4));
     listBox1.Items.Add(keys.Last());
 }

答案 1 :(得分:2)

你可以使用这样的函数:

static IEnumerable<string> Mutate(string input)
{
  if (input == null || input.Length == 0) { yield break; }
  yield return input;
  int pos = 0;
  while (pos < input.Length)
  {
    int index = input.IndexOf("Stop", pos);
    if (index == -1 || index == input.Length - 4) { yield break; }
    index += 4;
    yield return input.Substring(index);
    pos = index;
  }
}

然后做

string mRNA = textBox3.Text;
foreach (string key in Mutate(mRNA))
{
  listBox1.Items.Add(key);
}

我已经使用以下输入测试了此解决方案:

  • 为null,
  • 是空的,
  • 以“停止”开始,
  • 以“停止”结束,
  • 连续多个“停止”并且
  • 没有“停止”。

答案 2 :(得分:1)

Split可能是最过度使用的构造之一。很容易理解为什么,因为它实际上将问题分成几个部分,这就是当您进行鸟瞰时编程的全部内容。

但是,在这种情况下,最好使用Match and NextMatch搜索字符串:

  

此方法返回输入中与正则表达式模式匹配的第一个子字符串。您可以通过重复调用返回的Match对象的Match.NextMatch方法来检索后续匹配。

然后你可以使用Match#Index + Match#Length来找到“键”的索引(至少如果这是匹配后的所有内容,正如你所指出的那样)。然后可以使用String#Substring简单地检索密钥本身。

所以这是示例代码(因为你已经足够努力了,似乎):

var rna = "PhePheLeoArgStopValGlyArgTyrStopPheArgGleHis";
var pattern = "Stop";

var keys = new List<string>();

// the entire rna string is apparently also a key
keys.Add(rna);

Match match = Regex.Match(rna, pattern);

// loop while the pattern is found
while (match.Success)
{
    // we want everything after the match
    var from = match.Index + match.Length;
    keys.Add(rna.Substring(from));

    // and then retrieve the next match (if any)
    match = match.NextMatch();
}

你需要:

using System.Text.RegularExpressions;

在您的文件开头,以便工作。

如果您只是搜索静态字符串,也可以使用IndexOf。在这种情况下,您可以通过向找到的索引添加"Stop".Length来找到下一个字符串的开头(当然,在检查它是否实际找到Stop字符串之后)。

有关此示例,请查看at this answer