|
Три примера поиска и замены одного строкового
выражения другим
Первый пример показан на основе функций Split и Join.
SourceString - текст для поиска, ReplaceThis - какое искать
выражение в тексте, WithThis - на что менять найденное
выражение Пример 1
Function ReplaceAll(SourceString As String, ReplaceThis As String, WithThis As String)
Dim Temp As Variant
Temp = Split(SourceString, ReplaceThis)
ReplaceAll = Join(Temp, WithThis)
End Function
Private Sub Form_Load()
'этот пример меняет все найденные выражения
"go" на "bad", в тексте "good boy go home"
MsgBox ReplaceAll("good boy go home", "go", "bad")
End Sub
Пример 2
Public Function ReplaceAll(searchstring As String, findstring As String, replacestring As
String) As String
Dim curpos As Long
curpos = 1
Do
curpos = InStr(curpos, searchstring, findstring)
searchstring = Left$(searchstring, curpos - 1) & replacestring &
Right$(searchstring, Len(searchstring) - curpos - Len(findstring) + 1)
Loop Until InStr(searchstring, findstring) = 0
ReplaceAll = searchstring
End Function
Private Sub Form_Load()
MsgBox ReplaceAll("good boy go home", "go", "bad")
End Sub
Пример 3
Private Function ReplaceSubString(str As String, ByVal substr As String, ByVal newsubstr
As String)
Dim pos As Double
Dim startPos As Double
Dim new_str As String
startPos = 1
pos = InStr(str, substr)
Do While pos > 0
new_str = new_str & Mid$(str, startPos, pos - startPos) & newsubstr
startPos = pos + Len(substr)
pos = InStr(startPos, str, substr)
Loop
new_str = new_str & Mid$(str, startPos)
ReplaceSubString = new_str
End Function
Private Sub Command1_Click()
Text1.Text = ReplaceSubString(Text1.Text, " <", "<>")
'Примеры использования
'Text1.Text = ReplaceSubString(Text1.Text, ">" & vbCrLf,
">")
'Text1.Text = ReplaceSubString(Text1.Text, "><", ">" &
vbCrLf & "<")
'Text1.Text = ReplaceSubString(Text1.Text, vbCrLf, "")
'Text1.Text = ReplaceSubString(Text1.Text, "><", ">" &
vbCrLf & "<")
End Sub
|
|