Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

Chapter 21

The System.Text.RegularExpressions namespace

Regular expression functionality in Visual Basic .NET is contained in objects that are part of the System.Text.RegularExpressions namespace. Before looking at those classes, a very simple Visual Basic .NET regular expressions example is laid out.

There are several ways to use regular expressions in Visual Basic .NET. The following example uses one technique to carry out simple matching.

A Simple Visual Basic .NET Example

This example simply tests whether a string entered by the user matches a literal regular expression pattern, Fred.

The sample file, Module1.vb in the FindFred project, contains the following code:

Imports System.Text.RegularExpressions

Module Module1

Sub Main()

Dim myInput, myRegex myRegex = New Regex(“Fred”)

Console.WriteLine(“Enter a test string”) Console.WriteLine(“Then press the Enter key to continue.”) myInput = Console.ReadLine()

Console.WriteLine(“The string you entered was: “ & myInput) Console.WriteLine(“The match is: “ & myRegex.Match(myInput).Value) Console.WriteLine(“Press the Return key to continue.”) Console.ReadLine()

End Sub End Module

In some examples, the lines of code may break on the printed page when, in the original code, they exist on a single line. This difference is caused by the relatively limited line length on the printed page.

The following instructions assume that you have Visual Studio 2003 installed.

1.Open Visual Studio 2003, and from the File menu, select New; then select Project.

Figure 21-1 shows the dialog box that opens. The choices specified in Steps 2 through 4 are already made.

2.In the dialog box shown in Figure 21-1, select Visual Basic Projects in the Project Types pane.

3.Select Console Application in the Templates pane, and enter the text FindFred in the Name text box.

4.In the Location text box, enter the text C:\BRegExp\Ch21. If you wish, you can select another location. Click the OK button.

Figure 21-2 shows the screen’s appearance after clicking OK. The exact appearance may differ from that shown in the figure due to the many customization options available in Visual Studio 2003.

486

Visual Basic .NET and Regular Expressions

Figure 21-1

Figure 21-2

487

Chapter 21

The Regex object is part of the System.Text.RegularExpressions namespace. It is useful for conciseness of the code to import the System.Text.RegularExpressions namespace, using the Imports statement.

5.Add the following code to the code window, making sure that you add it before the line containing Module Module1:

Imports System.Text.RegularExpressions

6.Add the following code after the line that contains Sub Main():

Dim myInput, myRegex myRegex = New Regex(“Fred”)

Console.WriteLine(“Enter a test string”) Console.WriteLine(“Then press the Enter key to continue.”) myInput = Console.ReadLine()

Console.WriteLine(“The string you entered was: “ & myInput) Console.WriteLine(“The match is: “ & myRegex.Match(myInput).Value) Console.WriteLine(“Press the Return key to continue.”) Console.ReadLine()

7.From the File menu, select Save All. (You can use the Ctrl+Shift+S keyboard shortcut if you prefer.)

8.Press the F5 key to run the code. If you have entered the code correctly, you should see a console window open with the appearance shown in Figure 21-3.

Figure 21-3

9.At the command line, type Does anyone here know Fred?. Then press the Return key, and inspect the information that is displayed, as shown in Figure 21-4.

Figure 21-4

How It Works

Steps 1 through 4 create the skeleton for a console (command window) application.

The code added in Step 5 allows the classes contained in the System.Text.RegularExpressions namespace to be referred to simply by the name of the class, rather than the fully qualified name, such as

System.Text.RegularExpressions.Regex:

Imports System.Text.RegularExpressions

488

Visual Basic .NET and Regular Expressions

In this example, where the Regex object is used only once, importing the System.Text

.RegularExpressions namespace doesn’t save time. In more complex examples, importing the namespace does help to save developer time, because you’re writing code such as:

myRegex = New Regex(“Fred”)

rather than:

myRegex = New System.Text.RegularExpressions.Regex(“Fred”)

Both pieces of code do the same thing, but the first example makes the code easier to write and to read.

The code added inside Sub Main() defines what the console application does. First, two variables, myInput and myRegex, are dimensioned (declared). If OPTION STRICT had been set to ON, it would have been necessary to specify the type of each variable:

Dim myInput, myRegex

Next, a Regex object is instantiated and is passed the literal pattern Fred in the constructor. Instantiating a Regex object is one of the ways you can make regular expression functionality available in Visual Basic .NET:

myRegex = New Regex(“Fred”)

Then Console.WriteLine() is used twice to display simple instructions for the user:

Console.WriteLine(“Enter a test string”)

Console.WriteLine(“Then press the Enter key to continue.”)

Then the user input is read from the command window when the Return key is pressed, using the Console.ReadLine() method, and the value is assigned to the variable myInput:

myInput = Console.ReadLine()

Then the string that the user entered, contained in the variable myInput, is echoed to the command window using Console.WriteLine():

Console.WriteLine(“The string you entered was: “ & myInput)

The Match() method of the Regex object is used to match against the character sequence held in the myInput variable. The Console.WriteLine() method is used to display some explanatory text and the result of the matching process, in this case, the character sequence Fred:

Console.WriteLine(“The match is: “ & myRegex.Match(myInput).Value)

A message is displayed telling the user what to do to move the application on:

Console.WriteLine(“Press the Return key to continue.”)

Making the command window wait for user input allows the output of the earlier parts of the application to be displayed until such time as the user is ready to close the application:

Console.ReadLine()

489