c# - 通过循环查找多个括号
问题描述
我有一段代码用于分隔数据,当找到'('括号,但我想为多个括号发生时这样做
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))"
解决方案
这将提取括号内的所有字符串。
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)
推荐阅读
- r - 如何将 ISO-4217-Code 转换为 R 中的货币名称
- azure-logic-apps - 如何使用过滤器数组过滤来自 API 调用的数据?
- javascript - Firebase val() returns an empty object but when I use the console after the page is loaded, the object is there
- javascript - 返回具有最小属性值的对象键
- c# - MediatR 抽象基本命令
- azure-devops - ADO - 让一个跨多个分支的管道触发另一个管道
- mysql - 什么可能导致 mysql db read 返回陈旧数据
- mysql - 带有 TRIGGER 语法的 mySQL 错误代码 1136
- r - 使用多根求解 R 中的积分方程组
- python - 函数返回语句中的语法错误