2012-12-29 107 views
1

我想找到單詞並使用正則表達式替換它們。我不斷得到一個堆棧溢出異常,我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
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 
+1

嗨,傑里米,謝謝你爲我做這件事。我不得不更改if語句並從回車中刪除換行符,並編輯您的帖子以反映這一點。我在說你是一名C#程序員。不管怎樣,非常感謝,它工作得很好。 :) – user1632018

2

你的問題是,當有人改變文本,它會做一個替換。替換更改文字。然後您的事件處理程序再次被調用。等等等等,直到你用完堆棧空間,你會得到無限的遞歸,導致堆棧溢出。

爲了解決這個問題,請在方法調用之間保留一個布爾值。如果確實如此,請儘早退出事件處理程序。否則,將其設置爲true,並且當您離開事件處理程序時,將其設置爲false。

相關問題