您的应用程序需要在按钮单击之间至少保留足够的状态以突出显示下一个或上一个匹配项。我建议使用“匹配”正则表达式方法预先提取所有匹配项的集合,然后将该集合保留为您使用点击处理程序访问的状态变量。看起来像这样:
Public Class Form1
Private RegexPattern As String = "sample"
Private MatchState As MatchCollection 'The current state of all matches
Private MatchPosition As Integer 'The current index into the MatchState collection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'Put some sample text in the RTB
Me.RichTextBox1.Text = "Here sample is sample some sample text sample."
'Load the initial state of the application
Me.MatchState = Regex.Matches(Me.RichTextBox1.Text, Me.RegexPattern)
'Highlight the first match
Me.MatchPosition = 0
Me.HighlightCurrentPosition()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Move the match backward
Me.MatchPosition -= 1
If Me.MatchPosition < 0 Then
Me.MatchPosition = Me.MatchState.Count - 1
End If
Me.HighlightCurrentPosition()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Move the match forward
Me.MatchPosition += 1
If Me.MatchPosition >= Me.MatchState.Count Then
Me.MatchPosition = 0
End If
Me.HighlightCurrentPosition()
End Sub
Private Sub HighlightCurrentPosition()
If Me.MatchPosition >= 0 And Me.MatchPosition < Me.MatchState.Count Then
Dim match = Me.MatchState(Me.MatchPosition)
Me.RichTextBox1.Focus()
Me.RichTextBox1.Select(match.Index, match.Length)
End If
End Sub
End Class
You'll have to decide which event in your app's lifecycle makes the most sense to run the regex to generate the state. Here I just ran it when the form loads but you can adapt it to whatever works for you.