当找到'('括号时,我有一段代码用于分隔数据,但是我想对多个括号进行处理
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 "";
}
我想对多个brakcet这样做
像string="A+(B+(C*D))"
答案 0 :(得分:-1)
这将提取括号内的所有字符串。
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)