|
|
Title | Use regular expressions |
Description | This example shows how to use regular expressions in Visual Basic 6. |
Keywords | regular expression, string, parsing, parse |
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 changes the text in the txtString text box, the program makes a RegExp object. It sets the object's Pattern property to the value in the txtPattern text box. It then calls the object's Test method to see if the string in the txtString text box matches the pattern.
|
|
Private Sub txtString_Change()
Dim reg_exp As New RegExp
reg_exp.Pattern = txtPattern.Text
If reg_exp.Test(txtString.Text) Then
txtString.BackColor = vbWhite
Else
txtString.BackColor = vbYellow
End If
End Sub
|
|
The example program starts with the regular expression "^([2-9]{3}-)?[2-9]{3}-\d{4}$". The pieces of this expression have the following meanings:
^ | Match the beginning of the string |
[2-9]{3}- | Match the characters 2 through 9 exactly 3 times, followed by a - |
([2-9]{3}-)? | Match the expression "[2-9]{3}-" zero or 1 times |
[2-9]{3}- | Again, match the characters 2 through 9 exactly 3 times, followed by a - |
\d{4} | Match any digit exactly 4 times |
$ | Match the end of the string |
The result is that the string must have the form 222-2222 or 222-222-2222.
|
|
|
|
|
|