Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleUse regular expressions to replace text in a string
DescriptionThis 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.
Keywordsregular expression, string, parsing, parse, replace, RegExp
CategoriesStrings, 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.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated