首页 > 解决方案 > 通过循环查找多个括号

问题描述

我有一段代码用于分隔数据,当找到'('括号,但我想为多个括号发生时这样做

private void button1_Click(object sender, EventArgs e)
{
    string str = "A+(B*C)*D";
    string a=getBetween(str, "(", ")");
    str = str.Replace(a, "()");
    MessageBox.Show("string is=" + a);
    MessageBox.Show("string is=" + str);
}

}
public string getBetween(string strSource, string strStart, string strEnd)
{
   int Start, End;
   if (strSource.Contains(strStart) && strSource.Contains(strEnd))
   {
       Start = strSource.IndexOf(strStart, 0) + strStart.Length;
       End = strSource.IndexOf(strEnd, Start);
       return "(" +strSource.Substring(Start, End - Start)+")";
   }
   else
   {
      return "";

   }

我想为多个括号做它,比如string="A+(B+(C*D))"

标签: c#

解决方案


这将提取括号内的所有字符串。

public IEnumerable<string> Extract(string sourceStr, string startStr, string endStr)
{
    var startIndices = IndexOfAll(sourceStr, startStr).ToArray();
    var endIndices = IndexOfAll(sourceStr, endStr).ToArray();
    if(startIndices.Length != endIndices.Length)
        throw new InvalidOperationException("Missmatch");

    for (int i = 0; i < startIndices.Length; i++)
    {
        var start = startIndices[i];
        var end = endIndices[endIndices.Length - 1 - i];
        yield return sourceStr.Substring(start, end - start + 1);
    }
}

public static IEnumerable<int> IndexOfAll(string source, string subString)
{
    return Regex.Matches(source, Regex.Escape(subString)).Cast<Match>().Select(m => m.Index);
}

所以A+(B+(C*D))会返回两个字符串(B+(C*D))(C*D)


推荐阅读