Insomniac
Insomniac

Reputation: 57

Search for a Word in a RichTextbox and set its forecolor in VB.NET

I have made a program that displays an example of a particular piece of code. The available pieces of code come from a database. When the user selects an example the code itself is displayed in a RichTextbox. I also want the words to have coloring just like it would in the compiler.

I have a list of words and their associated RGB colors. I have another method which loops through the list of words and sends each one to this function:

Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
    If r > -1 And g > -1 And b > -1 And SearchString <> "" Then
        Dim richText As String = rtxtCode.Text.ToLower() 'store the rtxtCode as all lower case
        Dim keyText As String = SearchString.ToLower()   'store the SearchString as all lower case
        Dim wordIndex As Integer = 0

        While (wordIndex < richText.LastIndexOf(keyText, StringComparison.InvariantCultureIgnoreCase)) 'loop through each of the instances of the lowercase searchString in the lowercase textbox 
            wordIndex = richText.IndexOf(keyText, wordIndex) 'get the index of the next instance of the search string
            rtxtCode.SelectionStart = wordIndex 'select the text that contains the search string
            rtxtCode.SelectionLength = keyText.Length
            rtxtCode.SelectionColor = Color.FromArgb(r, g, b) 'give the selected string color
            rtxtCode.SelectionFont = New Font("Verdana", 9, FontStyle.Regular)
            wordIndex = wordIndex + keyText.Length + 1
        End While
    Else
        MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
    End If
End Sub

This works perfectly well. EXCEPT it does not find the occurrence of a word when it is the very first word. When the word begins at character index 0 in the RichTextbox, it cannot find the word. It will find every occurrence of the word after character index 0.

How can I correct this so that it finds words even at index 0?

Upvotes: 0

Views: 196

Answers (2)

Insomniac
Insomniac

Reputation: 57

This code correctly finds each occurrence of a word. Even when the word begins at char index 0. You must Imports System.Text.RegularExpressions to use Regex.

Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
  If r > -1 And g > -1 And b > -1 And SearchString <> "" Then

    Dim pattern As String = SearchString
    Dim regx As New Regex(pattern, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
    Dim matches As MatchCollection = regx.Matches(rtxtCode.Text)

    For Each match As Match In matches
        rtxtCode.Select(match.Index, match.Length)
        rtxtCode.SelectionColor = Color.FromArgb(r, g, b) 'give the selected string color
    Next

  Else
    MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
  End If
End Sub

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

Here's your original code refactored a bit, and searching forwards instead of backwards. It already can do a case-insensitive match, you don't have to convert to all lower case:

Private Sub FindAndFormatWords(ByVal SearchString As String, ByVal r As Integer, ByVal g As Integer, ByVal b As Integer)
    If r > -1 And g > -1 And b > -1 And SearchString <> "" Then
        Dim C As Color = Color.FromArgb(r, g, b)
        Dim F As New Font("Verdana", 9, FontStyle.Regular)
        Dim wordIndex As Integer = rtxtCode.Find(SearchString, 0, RichTextBoxFinds.NoHighlight)
        While (wordIndex <> -1)
            rtxtCode.SelectionStart = wordIndex
            rtxtCode.SelectionLength = SearchString.Length
            rtxtCode.SelectionColor = C
            rtxtCode.SelectionFont = F
            wordIndex = wordIndex + SearchString.Length
            If (wordIndex < rtxtCode.Text.Length) Then
                wordIndex = rtxtCode.Find(SearchString, wordIndex, RichTextBoxFinds.NoHighlight)
            Else
                wordIndex = -1
            End If
        End While
    Else
        MessageBox.Show("Error (1013): " & SearchString & " failed. Missing information.")
    End If
End Sub

Upvotes: 1

Related Questions