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

Visual Basic .NET and Regular Expressions

The myMatch variable is dimensioned as a Match object:

Dim myMatch As Match

Then each Match object in the myMatchCollection variable is processed in the same way using a For Each loop:

For Each myMatch In myMatchCollection

The Index property of the Match object is used to display the position in the string at which each match occurs. The Match object’s ToString() method returns the character sequence contained in a Match object:

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”, myMatch.Index, myMatch.ToString)

Next

Using the Match.Success Property and Match.NextMatch Method

The MatchCollection object just described provides one way to iterate through matches in a test string. An alternative approach to looping through the matches in a test string is to use the Match object’s Success property together with the Match object’s NextMatch method.

Try It Out

The Match.Success Property and Match.NextMatch Method

The content of Module1.vb in the NextMatchDemo project is shown here:

Imports System.Text.RegularExpressions

Module Module1

Sub Main()

Dim myRegex = New Regex(“[A-Z]\d”) Console.WriteLine(“Enter a string on the following line:”) Dim inputString = Console.ReadLine()

Dim myMatch = myRegex.Match(inputString) Dim myMatchCount As Integer

Console.WriteLine(“The first match is {0}.”, myMatch.ToString) Do While myMatch.Success

myMatchCount += 1

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”, myMatch.Index, myMatch.ToString)

myMatch = myMatch.NextMatch

Loop

Console.WriteLine(“There were {0} matches.”, myMatchCount) Console.WriteLine()

Console.WriteLine(“Press Return to close this application.”) Console.ReadLine()

End Sub

End Module

495

Chapter 21

1.Open Visual Studio, and create a new project. Name the project NextMatchDemo.

2.In the code window for Module1.vb, make edits to produce the content shown in the preceding

Module1.vb file.

3.Save the Module1.vb file, and press F5 to run the code.

4.Enter the test text Hello K9, K10 and K21. at the command line, and press the Return key. Inspect the results, as shown in Figure 21-7.

Figure 21-7

How It Works

The same regular expression pattern used in the preceding example is assigned to an instantiated Regex object in the myRegex variable:

Dim myRegex = New Regex(“[A-Z]\d”)

The test string is accepted from the user, and that string is assigned to the variable inputString. Then the Match() method of MyRegex is used to match the pattern [A-Z]\d against inputString:

Dim myMatch = myRegex.Match(inputString)

A variable myMatchCount is dimensioned. It will be used to count how many successful matches there are:

Dim myMatchCount As Integer

The value of the first match is output:

Console.WriteLine(“The first match is {0}.”, myMatch.ToString)

A Do While loop uses the Success property of the myMatch variable to process each successful match:

Do While myMatch.Success

The loop counter variable, myMatchCount, is incremented by 1:

myMatchCount += 1

Then the position and value of the match are displayed, using the Index property and ToString() method:

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”,

myMatch.Index, myMatch.ToString)

Then the NextMatch() method is used to test whether or not there is another match. If there is another match, when the myMatch.Success test in the Do While statement is evaluated, the Boolean value

496

Visual Basic .NET and Regular Expressions

True is returned, and the loop is processed again. If there is no match, myMatch.Success returns the Boolean value of False, and the loop is exited:

myMatch = myMatch.NextMatch

Loop

After the loop is exited, the value of the myMatchCount variable is used to display the number of matches found:

Console.WriteLine(“There were {0} matches.”, myMatchCount)

This technique provides an alternative to using the MatchCollection object when iterating through a collection of matches in a test string.

The GroupCollection and Group Classes

The patterns used in the preceding examples in this chapter have been very simple. More typically, parentheses in a pattern create groups. All the groups in a match are contained in a GroupCollection object. Each group in the collection is contained in a Group object.

Try It Out

The GroupCollection and Group Classes

The content of Module1.vb in the GroupsDemo project is shown here:

Imports System.Text.RegularExpressions

Module Module1

Sub Main()

Dim myRegex = New Regex(“([A-Z])(\d+)”) Console.WriteLine(“Enter a string on the following line:”) Dim inputString = Console.ReadLine()

Dim myMatchCollection = myRegex.Matches(inputString) Console.WriteLine()

Console.WriteLine(“There are {0} matches.”, myMatchCollection.Count) Console.WriteLine()

Dim myMatch As Match

Dim myGroupCollection As GroupCollection Dim myGroup As Group

For Each myMatch In myMatchCollection

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”, myMatch.Index, myMatch.ToString)

myGroupCollection = myMatch.Groups For Each myGroup In myGroupCollection

Console.WriteLine(“Group containing ‘{0}’ found at position ‘{1}’.”, myGroup.Value, myGroup.Index)

Next Console.WriteLine()

Next Console.WriteLine()

Console.WriteLine(“Press Return to close this application.”) Console.ReadLine()

End Sub

End Module

497

Chapter 21

1.Create a new project in Visual Studio 2003. Name the new project GroupsDemo.

2.In the code window for Module1.vb, make edits to produce the content shown in the preceding

Module1.vb file.

3.Save the code, and press F5 to run the code.

4.In the command window, enter the test string Hello K9, K10, K21 and K999.

5.Press the Return key, and inspect the displayed results, as shown in Figure 21-8.

Figure 21-8

How It Works

The regular expression pattern in this example includes two pairs of parentheses. Notice, too, that the pattern will now match one or more numeric digits, rather than matching exactly one numeric digit:

Dim myRegex = New Regex(“([A-Z])(\d+)”)

The user is asked to enter a test string as in the previous examples, and the Regex object’s Matches() method is used to match the inputString variable against the pattern contained in the myRegex variable:

Dim myMatchCollection = myRegex.Matches(inputString)

A variable, myGroupCollection, is dimensioned as a GroupCollection object:

Dim myGroupCollection As GroupCollection

A variable, myGroup, is dimensioned as a Group object:

Dim myGroup As Group

Two For Each loops are used. The outer For Each loop is used to iterate through the Match objects in the MatchCollection object:

For Each myMatch In myMatchCollection

498