16.4 The Regex ClassThe .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 expressionsImports 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.
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. |