How to match a pattern using regular expressions in Visual Basic .NET or in Visual Basic 2005 (301264)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Studio .NET (2003), Professional Edition
  • Microsoft Visual Studio .NET (2002), Professional Edition

This article was previously published under Q301264
For a Microsoft C# .NET version of this article, see 308252.

IN THIS TASK

SUMMARY

This article demonstrates how to create and use regular expressions to determine whether strings match certain patterns. Regular expressions allow for easy parsing and matching of strings to a specific pattern. Using the objects available in the RegularExpressions namespace, you can compare a string against a given pattern, replace a string pattern with another string, or retrieve only portions of a formatted string. In this example, we will construct a pattern to validate a e-mail address.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you will need:
  • Microsoft Visual Basic .NET or Microsoft Visual Basic 2005
This article assumes the following:
  • An understanding of Visual Basic .NET or Visual Basic 2005
  • A basic understanding of regular expression syntax
back to the top

Using Regular Expressions to Match a Pattern

  1. Open Visual Studio .NET or Visual Studio 2005.
  2. Create a new Visual Basic .NET or Visual Basic 2005 Console Application.
  3. Use the Imports statement on the Text.RegularExpressions namespace so that you will not be required to qualify declarations in those namespaces later in your code. The Imports statement must be used prior to any other declarations:
    Imports System.Text.RegularExpressions
    					
  4. The string that we will compare against the regular expression pattern will be passed as a command-line argument. In Visual Basic .NET or in Visual Basic 2005, we need to call the GetCommandLineArgs method to retrieve the data passed in as a command-line argument. Add this code to the Main procedure in the Module1.
    Dim Args As String() = System.Environment.GetCommandLineArgs()
    					
  5. Define a new regular expression that will use a pattern match to validate an e-mail address. The following regular expression is structured to accomplish three things:
    1. Capture the substring before the @ symbol and put that into the "user" group.
    2. Capture the substring after the @ symbol and put that into the "host" group.
    3. Make sure that the first half of the string does not have an @ symbol.
    Dim EmailRegex As Regex = New Regex("(?<user>[^@]+)@(?<host>.+)")
    					
  6. Define a new string containing a valid e-mail address. This provides a default value if the method's command-line argument is empty:
    Dim S As String = "johndoe@tempuri.org"
    					
  7. Check to see if there are any command-line parameters; if there are, retrieve the first parameter and assign it to the variable "s".
    If Args.Length > 1
    	S = Args(1)
    End If
    					
  8. Use the Match method to pass in the e-mail address variable and return a new Match object. The Match object will return regardless of whether any matches were found in the source string.
    Dim M As Match = EmailRegex.Match(S)
    					
  9. By examining the Success property, we can decide whether to continue processing the Match object or to print an error message. If successful, display the "user" and "host" named groups within the Groups collection of the Match object.
    If M.Success
    	Console.WriteLine("User: " & M.Groups("user").Value)
    	Console.WriteLine("Host: " & M.Groups("host").Value)
    Else
    	Console.WriteLine(s & " is not a valid email address")
    End If
    Console.WriteLine()
    					
  10. To keep the console window open after running the application, add the following lines of code:
    Console.WriteLine("Hit <enter> to exit...")
    Console.ReadLine()
    					
  11. Build your project.
  12. To run the application in the development environment using the default e-mail address specified in the code, press F5 or click Start from the Debug menu. To start the application with a command-line argument, there are two options:
    1. Start a command window and navigate to the "bin" folder under the folder in which your project resides. Then type in the name of the executable followed by the e-mail address you wish to test.
    2. Locate the executable file for this project, and drag it to the Start...Run window on the taskbar. Add the e-mail address to verify, and click or press OK.
back to the top

REFERENCES

back to the top

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005swept kbvs2005applies kbHOWTOmaster KB301264 kbAudDeveloper