7,764
社区成员
发帖
与我相关
我的任务
分享
string RemoveParenthesis(string pamam)
{
string result = pamam;
while (Regex.IsMatch(result, @"\(\(.+?\)\)"))
{
Match match = Regex.Match(result, @"\((\(.+?\))\)");
result = result.Replace(match.Groups[0].Value, match.Groups[1].Value);
}
return result;
}
string str = "1+(((((3-5))+((2)))))+2";
string result = RemoveParenthesis(str);
//result为:1+(3-5)+(2)+2
\(([\+\-]?\d*?)\)
Private Sub TestReg()
Dim strData As String
Dim reg As Object
strData = "1889/((((845-59)+((4999)()×((93(-)599)())+((62))())÷62))+666662)"
Set reg = CreateObject("vbscript.regExp")
reg.Global = True
reg.Pattern = "\((.?|\d+)\)"
Do While reg.Execute(strData).Count > 0
strData = reg.Replace(strData, "$1")
Loop
Debug.Print strData
End Sub
输出:\((.?|\d+|[\+\-*/]\d+)\)
Private Sub Form_Load()
Dim s$, i%, isContinue As Boolean, i1%, i2%
s = "1/((((8-5)+((4)()×((3(-)5)())+((2))())÷2))+2)"
Do
isContinue = False
For i = 1 To Len(s)
If Mid(s, i, 1) = "(" Then
i1 = getMatch(s, i)
i2 = IIf(Mid(s, i + 1, 1) = "(", getMatch(s, i + 1), i1)
If i1 - i2 = 1 Or i2 - i <= 2 Then
s = Left(s, i - 1) & Mid(s, i + 1, i2 - i - 1) & Mid(s, i2 + 1)
isContinue = True
End If
End If
Next
Loop Until Not isContinue
Debug.Print s
End Sub
'得到匹配的括号的位置
Private Function getMatch(strKey$, intPos%) As Integer
Dim i%, intLCount%, intRCount%
For i = intPos To Len(strKey)
If Mid(strKey, i, 1) = "(" Then
intLCount = intLCount + 1
ElseIf Mid(strKey, i, 1) = ")" Then
intRCount = intRCount + 1
If intRCount = intLCount Then
getMatch = i
Exit Function
End If
End If
Next
End Function