I am trying to find words and replace them using regex. I keep getting a stack overflow exception, I am geussing is due to a recursive loop. So I tried removing the for loop from the first block of code, and came up with the second block of code and still the same issue.
I am trying to find certain strings while ignoring case and automatically replace them with the right case of the same string. So an example would be that someone types in “vB” it would automatically replace it with “vb”. I know my issue has to due with being in the textchanged event so if someone could guide me in the right direction I would be very thankful.
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
After replacing the For loop.
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
1 Answer