1

我正在尝试查找单词并使用正则表达式替换它们。我不断收到堆栈溢出异常,我猜是由于递归循环。所以我尝试从第一个代码块中删除 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
4

2 回答 2

2

您的问题是,当有人更改文本时,它会进行替换。替换会更改文本。然后再次调用您的事件处理程序。等等等等。你会得到无限递归,直到你用完堆栈空间,导致堆栈溢出。

为了解决这个问题,在方法调用之间保留一个布尔值。如果为真,请尽早退出事件处理程序。否则,将其设置为 true,当您离开事件处理程序时,将其设置为 false。

于 2012-12-29T03:44:46.410 回答
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
于 2012-12-29T03:55:56.213 回答