Recipe 5.39. Getting the Nth Regular Expression Match


Problem

You want to get the nth match of a regular expression search within a string.

Solution

Sample code folder: Chapter 05\RegexMatchN

Use the Regex object to return a MatchCollection based on the regular expression. The nth match is accessed by indexing item n1 in the collection.

Discussion

The following code finds all numbers in a sample string, returning all matches as a MatchCollection. In this example, the regular expression accesses the third match in the zero-based collection as item number 2:

 Imports System.Text.RegularExpressions ' …Later, in a method… Dim source As String = "This 7. string -0.02 " & _    "contains 003.141600 several 0.9 numbers" Dim parser As New Regex( _    "[-+]?([0-9]*\.)?[0-9]+([eE][-+]?[0-9]+)?") Dim sourceMatches As MatchCollection = _    parser.Matches(source) Dim result As Double = CDbl(sourceMatches(2).Value) MsgBox(source & vbNewLine & "The 3rd number: " & _    result.ToString()) 

Figure 5-44 shows the third number found in the string.

Figure 5-44. Using a regular expression to find the nth match in a string


See Also

Recipe 5.37 discusses the specific regular expression pattern used in this recipe.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net