|
|
Title | Use regular expressions to replace text in a string |
Description | This example shows how to use regular expressions to replace text in a string in Visual Basic 6. The program uses the RegExp class's Replace method. |
Keywords | regular expression, string, parsing, parse, replace, RegExp |
Categories | Strings, Algorithms |
|
|
Before using regular expressions, select the Project menu's References command and select the Microsoft VBScript Regular Expressions 1.0" library.
When the user clicks the Go button, the program makes a RegExp object. It sets the object's Pattern property to the value in the txtPattern text box and sets its IgnoreCase property to True.
If the Global check box is checked, then the program sets the object's Global property to True to make the replacement affect all occurrances of the pattern. If this is False, the replacement only affects the first match.
The program finishes by calling the Replace method and displaying the result.
|
|
Private Sub cmdGo_Click()
On Error Resume Next
Dim reg_exp As New RegExp
reg_exp.Pattern = txtPattern.Text
reg_exp.IgnoreCase = True
' If the Global check box is checked,
' then set the Global property to True
' to make the replacement affect all
' occurrances of the pattern.
reg_exp.Global = (chkGlobal.Value = vbChecked)
' Make the replacement.
lblResult.Caption = reg_exp.Replace(txtString.Text, _
txtReplace.Text)
End Sub
|
|
In this example, the search pattern is "[aeiou]" and the replacement pattern is "." so the program replaces all instances of vowels with periods.
|
|
|
|
|
|