我有一个富文本框,我只想搜索和替换整个单词。
我有一些代码,但是我有一种感觉,我这样做的方式可能不允许只使用整个单词。
代码:
Dim search As String = TextBox1.Text
Dim replace1 As String = TextBox2.Text
Dim input As String
input = Form1.RichTextBox1.Text.Trim
Dim location As Integer
search = search.Trim()
replace1 = replace1.Trim()
location = input.IndexOf(search)
If location = -1 Then
MsgBox("Text not found", MsgBoxStyle.Exclamation, "Not Found")
Else
Form1.RichTextBox1.Text = input.Remove(location, search.Length).Insert(location, replace1)
MsgBox("Text " & search & " has been replaced with " & replace1, , )
End If
如果您有其他方法,请分享。
第二次尝试:现在有效,但是我只想找到整个单词。
Dim search As String = TextBox1.Text
Dim replace1 As String = TextBox2.Text
Dim input As String
input = Form1.RichTextBox1.Text.Trim
search = search.Trim()
replace1 = replace1.Trim()
If Regex.IsMatch(input, search) = True Then
Dim out As String = Regex.Replace(input, search, replace1)
Form1.RichTextBox1.Text = out
MsgBox(search & " has been replaced with " & replace1, MsgBoxStyle.Information, "Success")
Else
MsgBox("Not found", MsgBoxStyle.Exclamation, "Not Found")
End If
最终代码:
Dim search As String = TextBox1.Text
Dim replace1 As String = TextBox2.Text
Dim input As String
input = Form1.RichTextBox1.Text.Trim
search = search.Trim()
replace1 = replace1.Trim()
If Regex.IsMatch(input, " " & search & " ") = True Then
Dim out As String = Regex.Replace(input, " " & search & " ", " " & replace1 & " ")
Form1.RichTextBox1.Text = out
MsgBox(search & " has been replaced with " & replace1, MsgBoxStyle.Information, "Success")
GoTo line
Else
GoTo line3
MsgBox("Not found", MsgBoxStyle.Exclamation, "Not Found")
End If
line3:
If Regex.IsMatch(input, search & " ") = True Then
Dim out As String = Regex.Replace(input, search & " ", replace1 & " ")
Form1.RichTextBox1.Text = out
MsgBox(search & " has been replaced with " & replace1, MsgBoxStyle.Information, "Success")
GoTo line
Else
GoTo line2
MsgBox("Not found", MsgBoxStyle.Exclamation, "Not Found")
End If
line2:
If Regex.IsMatch(input, " " & search) = True Then
Dim out As String = Regex.Replace(input, " " & search, " " & replace1)
Form1.RichTextBox1.Text = out
MsgBox(search & " has been replaced with " & replace1, MsgBoxStyle.Information, "Success")
GoTo line
Else
MsgBox("Not found", MsgBoxStyle.Exclamation, "Not Found")
GoTo line
End If
line: