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 in VB .NET
DescriptionThis example shows how to use regular expressions in VB .NET. It uses the Regex class to validate text entered by the user.
Keywordsregular expression, string, parsing, parse
CategoriesStrings, Algorithms
 
When the user changes the text in the txtTestExp text box, the program makes a Regex object, passing the constructor the regular expression to match. It calls the object's IsMatch method, passing it the text that the user entered and sets the text box's background color to yellow if the text doesn't match the expression.
 
Private Sub txtTestExp_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    txtTestExp.TextChanged
    Dim reg_exp As New Regex(txtRegExp.Text)
    If reg_exp.IsMatch(txtTestExp.Text) Then
        txtTestExp.BackColor = Color.White
    Else
        txtTestExp.BackColor = Color.Yellow
    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.

Also note that the Regex class has a shared IsMatch method that you can use without creating a Regex object. Creating an object as in this example allows the object to compile the regular expression so it can later evaluate the expression more quickly. This is useful if you need to use the expression many times.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated