|
|
Title | Use regular expressions to replace characters within parts of a string surrounded by quotes in Visual Basic 6 |
Description | This example shows how to use regular expressions to replace characters within parts of a string surrounded by quotes in Visual Basic 6 |
Keywords | regular expression, regex, regexp, replace |
Categories | Algorithms, Strings |
|
|
This example uses a reference to the "Microsoft VBScript Regular Expression 5.5" library.
This example looks for parts of a string surrounded by double quotes and replaces occurrences of / with ? within those parts. The rest of the string also contains / so you can see that the code doesn't replace those instances.
When you click the Replace button, the program uses Regex.Matches to get a collection of matches for the pattern "[^"]*". This pattern matches a quote, followed by any number of non-quotes, followed by a quote.
For each match, the code adds the part of the input string between this match and the previous one and then the matched text with the appropriate replacement. After it has processed each match, the code adds any text remaining in the input string.
|
|
Private Sub cmdReplace_Click()
Dim txt As String
Dim result As String
Dim next_unmatched As Integer
Dim reg_exp As New RegExp
Dim a_match As Match
txt = txtInput.Text
result = ""
next_unmatched = 1
reg_exp.Pattern = txtPattern.Text
reg_exp.IgnoreCase = True
reg_exp.Global = True
For Each a_match In reg_exp.Execute(txt)
' Add the text before the next match.
If a_match.FirstIndex > next_unmatched Then
result = result & Mid$(txt, next_unmatched, _
a_match.FirstIndex - next_unmatched)
End If
' Add the matched text.
result = result & Replace(a_match.Value, "/", "?")
Debug.Print "[" & a_match.Value & "]"
' Set next_unmatched to the index
' of the last character in this match.
next_unmatched = a_match.FirstIndex + a_match.Length
Next a_match
' Add the rest of the string.
If Len(txt) > next_unmatched Then
result = result & Mid$(txt, next_unmatched)
End If
' Display the result.
txtResult.Text = result
End Sub
|
|
|
|
|
|