RichTextBox中效果图
/// <summary>
/// 记录代码中的括号,尖括号,方括号,大括号的配对位置
/// </summary>
/// <param name="sText"></param>
/// <param name="C_ExplanatoryNote_Pos">注释位置</param>
/// <returns></returns>
/// 创建时间: 2022-08-26 最后一次修改时间:2022-08-26
public static DList_<Pair_<int, int>> _Syntax_C_FindBrackets(this string sText, DList_<Pair_<int, int>> C_ExplanatoryNote_Pos)
{
//找出所有的 (, <, [,{ 然后配对
string sLeft = "(<[{";
DList_<Pair_<int, int>> dLeft = new DList_<Pair_<int, int>>();
for (int i = 0; i < sText.Length; ++i)
{
char cLeft = sText[i];
if(sLeft.IndexOf(cLeft) != -1)
{
dLeft.Add(new Pair_<int, int>(i, -1));
}
}
//查找配对
DListNote_<Pair_<int, int>> pNote = dLeft.First;
while (pNote != null)
{
Pair_<int, int> p = pNote.Data;
p.Second = _Syntax_C_NextBrackets(sText, p.First);
pNote = pNote.Next;
}
DList_<Pair_<int, int>> dResult = new DList_<Pair_<int, int>>();
pNote = dLeft.First;
while (pNote != null)
{
Pair_<int, int> p = pNote.Data;
if (p.Second != -1)
dResult.Add(p);
pNote = pNote.Next;
}
return dResult;
}
/// <summary>
/// 记录代码中的括号,尖括号,方括号,大括号的配对位置
/// </summary>
/// <param name="sText"></param>
/// <param name="nPos">配对左边位置</param>
/// <returns></returns>
public static int _Syntax_C_NextBrackets(this string sText, int nPos)
{
// ( 1 , ( 2 ) 1 2)
int iFlag = 0;
char cLeft = sText[nPos];
if (cLeft == '(')
{
for (int i = nPos + 1; i < sText.Length; ++i) //查找配对,直到遇到分号;
{
char cRight = sText[i];
if (cRight == ')')
{
if (iFlag == 0) { return i; }
-- iFlag;
}
else if (cRight == '(')
{
++ iFlag;
}
else if (cRight == ';')
{
break;
}
}
}
else if(cLeft == '<')
{
for (int i = nPos + 1; i < sText.Length; ++i) //查找配对,直到遇到分号;
{
char cRight = sText[i];
if (cRight == '>')
{
if (iFlag == 0) { return i; }
--iFlag;
}
else if (cRight == '<')
{
++iFlag;
}
else if (cRight == ';')
{
break;
}
}
}
else if (cLeft == '[') //上下标
{
for (int i = nPos + 1; i < sText.Length; ++i) //查找配对,直到遇到分号;
{
char cRight = sText[i];
if (cRight == ']')
{
if (iFlag == 0) { return i; }
--iFlag;
}
else if (cRight == '[')
{
++iFlag;
}
else if (cRight._IsPunctuation()) //遇到标点符号停止
{
break;
}
}
}
else if (cLeft == '{') //大括号查找全部文本
{
for (int i = nPos + 1; i < sText.Length; ++i) //查找配对,直到遇到分号;
{
char cRight = sText[i];
if (cRight == '}')
{
if (iFlag == 0) { return i; }
--iFlag;
}
else if (cRight == '{')
{
++iFlag;
}
}
}
return - 1;
}