Section 16.4. The Regex Class

   

16.4 The Regex Class

The .NET Framework provides an object-oriented approach to regular expression matching and replacement.

The Framework Class Library namespace System.Text.RegularExpressions is the home to all the .NET Framework objects associated with regular expressions. The central class for regular expression support is Regex, which represents an immutable, compiled regular expression. Example 16-9 rewrites Example 16-8 to use regular expressions and thus solves the problem of searching for more than one type of delimiter .

Example 16-9. Using the Regex class for regular expressions
 Imports System Imports System.Text Imports System.Text.RegularExpressions Namespace RegularExpressions     Class Tester         Public Sub Run( )             Dim s1 As String = "One,Two,Three Liberty Associates, Inc."             Dim theRegex As New Regex(" , ,")             Dim sBuilder As New StringBuilder( )             Dim id As Integer = 1             Dim subString As String             For Each subString In theRegex.Split(s1)                 id = id + 1                 sBuilder.AppendFormat("{0}: {1}"  _                   & Environment.NewLine, id, subString)             Next subString             Console.WriteLine("{0}", sBuilder)         End Sub 'Run         Public Shared Sub Main( )             Dim t As New Tester( )             t.Run( )         End Sub 'Main     End Class 'Tester End Namespace 'RegularExpressions 
  Output:  1: One 2: Two 3: Three 4: Liberty 5: Associates 6: Inc. 

Example 16-9 begins by creating a string, s1, identical to the string used in Example 16-8:

 Dim s1 As String = "One,Two,Three Liberty Associates, Inc." 

and a regular expression that will be used to search that string:

 Dim theRegex As New Regex(" , ,") 

One of the overloaded constructors for Regex takes a regular expression string as its parameter.

This can be a bit confusing. In the context of a VB.NET program, which is the regular expression: the text passed in to the constructor or the Regex object itself? It is true that the text string passed to the constructor is a regular expression in the traditional sense of the term . From an object-oriented VB.NET point of view, however, the argument to the constructor is just a string of characters ; it is the Regex object that is the regular expression object.

The rest of the program proceeds like the earlier Example 16-8, except that rather than calling the Split( ) method of String on string s1, the Split( ) method of Regex is called. theRegex.Split( ) acts in much the same way as String.Split( ), returning an array of strings as a result of matching the regular expression pattern within the Regex.

   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

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