我正在尝试查找单词并使用正则表达式替换它们。我一直得到一个堆栈溢出异常,我正在进行geussing是由于一个递归循环。所以我尝试从第一个代码块中删除for循环,并提出了第二个代码块,但问题仍然存在。
我试图找到某些字符串而忽略大小写并自动用相同字符串的正确大小写替换它们。所以一个例子是有人输入“vB”它会自动用“vb”替换它。我知道我的问题必须归功于textchanged事件,所以如果有人能指导我朝着正确的方向前进,我会非常感激。
Private Sub tb_textchanged(ByVal sender As System.Object, ByVal e As TextChangedEventArgs)
Dim pattern As String = "\<vb\>"
Dim input As String = txt.Text
For Each m As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
Dim caretpos As FastColoredTextBoxNS.Place = New Place(txt.Selection.Start.iChar, txt.Selection.Start.iLine)
Dim replacement As String = "<vb>"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement, RegexOptions.IgnoreCase)
txt.Text = result
txt.Selection.Start = New Place(caretpos.iChar, caretpos.iLine)
Next
End Sub
更换For循环后。
Private Sub tb_textchanged(ByVal sender As System.Object, ByVal e As TextChangedEventArgs)
Dim pattern As String = "\<vb\>"
Dim input As String = txt.Text
Dim matches As MatchCollection = Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
If matches.Count > 0 Then
Dim caretpos As FastColoredTextBoxNS.Place = New Place(txt.Selection.Start.iChar, txt.Selection.Start.iLine)
Dim replacement As String = "<vb>"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement, RegexOptions.IgnoreCase)
txt.Text = result
txt.Selection.Start = New Place(caretpos.iChar, caretpos.iLine)
End If
End Sub
答案 0 :(得分:2)
您的问题是,当有人更改文本时,它会替换。替换更改文本。然后再次调用您的事件处理程序。等等,你会得到无限的递归,直到你的堆栈空间不足,导致堆栈溢出。
要解决此问题,请在方法调用之间保留一个布尔值。如果是,请尽早退出事件处理程序。否则,将其设置为true,当您离开事件处理程序时,将其设置为false。
答案 1 :(得分:0)
Private isRecursive As Boolean
Private Sub tb_textchanged(ByVal sender As System.Object, ByVal e As TextChangedEventArgs)
If (isRecursive) Then
Return
End If
isRecursive = True
Dim pattern As String = "\<vb\>"
Dim input As String = txt.Text
Dim matches As MatchCollection = Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
If matches.Count > 0 Then
Dim caretpos As FastColoredTextBoxNS.Place = New Place(txt.Selection.Start.iChar, txt.Selection.Start.iLine)
Dim replacement As String = "<vb>"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement, RegexOptions.IgnoreCase)
txt.Text = result
txt.Selection.Start = New Place(caretpos.iChar, caretpos.iLine)
End If
isRecursive = False
End Sub