home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / 12 regular expressions / regexdemo / module1.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  14.3 KB  |  385 lines

  1. Imports System.Text.RegularExpressions
  2.  
  3. Module MainModule
  4.  
  5.     Sub Main()
  6.         ' Run one of the Textxxxx procedures below by uncommenting only one statement
  7.  
  8.         'TestSearchReplace()
  9.         'TestReplace()
  10.         'TestRegexOptions()
  11.         'TestRegexOptions2()
  12.         'TestRegex()
  13.         'TestReplace()
  14.         'TestReplaceWithCallback()
  15.         'TestSharedMethods()
  16.         'TestGroups()
  17.         'TestMatch()
  18.         'TestGroupObject()
  19.         'TestCaptureObject()
  20.         'TestCaptureObject2()
  21.         'TestSearchHyperlinks()
  22.  
  23.         ' These statements are usuful when running inside Visual Studio.NET
  24.         Console.WriteLine("")
  25.         Console.WriteLine(">>> type Enter to terminate the program <<<")
  26.         Console.ReadLine()
  27.     End Sub
  28.  
  29.     ' this procedure is the first example of regex
  30.  
  31.     Sub TestSearchReplace()
  32.         Dim re As New Regex("[aeiou]\d")
  33.         ' This source string contains 3 groups that match the Regex.
  34.         Dim source As String = "a1 = a1 & e2"
  35.         ' Get the collection of matches.
  36.         Dim mc As MatchCollection = re.Matches(source)
  37.         ' How many occurrences did we find?
  38.         Console.WriteLine("Found " & mc.Count & " occurrences")
  39.         ' => Found 3 occurrences.
  40.  
  41.         ' List position of each occurrence
  42.         Dim m As Match
  43.         For Each m In mc
  44.             ' Display text and position of this match.
  45.             Console.WriteLine("'{0}' at index {1}", m.ToString, m.Index)
  46.         Next
  47.  
  48.         ' test case insensitive searches
  49.         source = "ABC Abc abc"
  50.         mc = Regex.Matches(source, "abc")
  51.         Console.WriteLine(mc.Count)           ' => 1
  52.         mc = Regex.Matches(source, "abc", RegexOptions.IgnoreCase)
  53.         Console.WriteLine(mc.Count)           ' => 3
  54.  
  55.         source = "a1 = a1 & e2"
  56.         ' Search for the "a" character followed by a digit.
  57.         re = New Regex("a\d")
  58.         ' Drop the digit that follows the "a" character
  59.         Console.WriteLine(re.Replace(source, "a"))   ' => a = a & e2
  60.  
  61.         ' This code snippet is equivalent to the previous one, but doesn't
  62.         ' instantiate a Regex object.
  63.         Console.WriteLine(Regex.Replace("a1 = a1 & e2", "a\d", "a"))
  64.     End Sub
  65.  
  66.     ' this procedure tests Regex options - searches for variable assignments
  67.  
  68.     Sub TestRegexOptions()
  69.         ' modify this path to point to an existing .VB file
  70.         Dim source As String = FileText("c:\Module1.vb")
  71.         Dim pattern As String = "^\s*[A-Z]\w* ?=.+(?=\r\n)"
  72.  
  73.         ' Get the collection of all matches, in multiline mode.
  74.         Dim mc As MatchCollection = Regex.Matches(source, pattern, _
  75.             RegexOptions.IgnoreCase Or RegexOptions.Multiline)
  76.  
  77.         ' Display all variable assignments 
  78.         Dim m As Match
  79.         For Each m In mc
  80.             Console.WriteLine("[{0}]  {1}", m.Index, m.ToString)
  81.         Next
  82.     End Sub
  83.  
  84.     ' this procedure tests Regex options and search for variable declarations in VB files.
  85.  
  86.     Sub TestRegexOptions2()
  87.         ' modify this path to point to an existing .VB file
  88.         Dim source As String = FileText("c:\Module1.vb")
  89.         Dim pattern As String = "(?im)^\s+(dim|public|private) [A-Z]\w* As .+(?=\r\n)"
  90.  
  91.         ' Get the collection of all matches, in multiline mode.
  92.         Dim mc As MatchCollection = Regex.Matches(source, pattern, _
  93.             RegexOptions.IgnoreCase Or RegexOptions.Multiline)
  94.  
  95.         ' Display all variable declarations and their offset in source file.
  96.         Dim m As Match
  97.         For Each m In mc
  98.             Console.WriteLine("[{0}]  {1}", m.Index, m.ToString)
  99.         Next
  100.     End Sub
  101.  
  102.     ' Reusable function that reads the contents of a text file.
  103.  
  104.     Function FileText(ByVal path As String) As String
  105.         ' Open a file stream and define a stream reader.
  106.         Dim fs As System.IO.FileStream
  107.         Dim sr As System.IO.StreamReader
  108.  
  109.         Try
  110.             fs = New System.IO.FileStream(path, System.IO.FileMode.Open)
  111.             sr = New System.IO.StreamReader(fs)
  112.             ' Read the entire contents of this file.
  113.             FileText = sr.ReadToEnd
  114.         Catch ex As Exception
  115.             Console.WriteLine(ex.Message)
  116.         Finally
  117.             ' Clean-up code.
  118.             sr.Close()
  119.             fs.Close()
  120.         End Try
  121.     End Function
  122.  
  123.     ' this procedure tests various regex constructs
  124.  
  125.     Sub TestRegex()
  126.         ' Finds consecutive groups of space delimited numbers.
  127.         Dim re As New Regex("\G\s*\d+")
  128.         ' Note that search stops at the first non-numeric group.
  129.         Console.WriteLine(re.Matches("12 34 56 ab 78").Count)     ' => 3
  130.  
  131.         ' Check whether the input string is a date in the format mm-dd-yy or 
  132.         ' mm-dd-yyyy (can optionally use slashes as date separator and 
  133.         ' contain leading or trailing white spaces).
  134.         re = New Regex("^\s*\d{1,2}(/|-)\d{1,2}\1(\d{2}|\d{4})\s*$")
  135.         If re.IsMatch(" 12/10/2001 ") Then
  136.             Console.WriteLine("The date is formatted correctly.")
  137.             ' (We don't check whether month and day values are in valid range.)
  138.         Else
  139.             Console.WriteLine("The date is formatted incorrectly.")
  140.         End If
  141.  
  142.         ' Demonstrate the Match method
  143.         ' Search all the dates in a source string.
  144.         Dim source As String = " 12-2-1999  10/23/2001 4/5/2001 "
  145.         re = New Regex("\s*\d{1,2}(/|-)\d{1,2}\1(\d{2}|\d{4})")
  146.  
  147.         ' Find the first match.
  148.         Dim m As Match = re.Match(source)
  149.         ' Enter the following loop only if the search was successful.
  150.         Do While m.Success
  151.             Console.WriteLine(m.ToString.Trim)
  152.             ' Find the next matches, exit if not successful.
  153.             m = m.NextMatch
  154.         Loop
  155.         Console.WriteLine("")
  156.  
  157.         source = "123, 456,,789"
  158.         re = New Regex("\s*,\s*")
  159.  
  160.         Dim s As String
  161.         For Each s In re.Split(source)
  162.             ' Note that the 3rd element is a null string.
  163.             Console.Write(s & "-")              ' => 123-456--789
  164.         Next
  165.     End Sub
  166.  
  167.     ' this procedure tests the Replace method
  168.  
  169.     Sub TestReplace()
  170.         Dim source As String = "12-2-99  10/23/2001  4/5/2001 "
  171.         Dim pattern As String = _
  172.             "\b(?<mm>\d{1,2})(?<sep>(/|-))(?<dd>\d{1,2})\k<sep>(?<yy>(\d{2}|\d{4}))\b"
  173.         Dim re As New Regex(pattern)
  174.         Console.WriteLine(re.Replace(source, "${dd}${sep}${mm}${sep}${yy}"))
  175.         ' => 2-12-1999  23/10/2001  5/4/2001
  176.  
  177.         ' Expand all "ms" abbreviations to "Microsoft", regardless of their case.
  178.         source = "Welcome to MS ms Ms MS"
  179.         re = New Regex("\bMS\b", RegexOptions.IgnoreCase)
  180.         ' Replace up to 3 occurrences, starting at 10th character.
  181.         Console.WriteLine(re.Replace(source, "Microsoft", 3, 10))
  182.         ' => Welcome to Microsoft Microsoft Microsoft MS
  183.     End Sub
  184.  
  185.     ' this procedure tests Replace with callback
  186.  
  187.     Sub TestReplaceWithCallback()
  188.         ' This pattern defines two integers separated by a + symbol.
  189.         Dim re As New Regex("\d+\s*\+\s*\d+")
  190.         Dim source As String = "a = 100 + 234: b = 200+345"
  191.         ' Replace all sum operations with their result.
  192.         Console.WriteLine(re.Replace(source, AddressOf DoSum))
  193.         ' => a = 334: b = 545
  194.     End Sub
  195.  
  196.     Function DoSum(ByVal m As Match) As String
  197.         ' Find the position of the "+" symbol.
  198.         Dim i As Integer = m.ToString.IndexOf("+"c)
  199.         ' Parse the two operands.
  200.         Dim n1 As Long = Long.Parse(m.ToString.Substring(0, i))
  201.         Dim n2 As Long = Long.Parse(m.ToString.Substring(i + 1))
  202.         ' Return their sum, as a string.
  203.         Return (n1 + n2).ToString
  204.     End Function
  205.  
  206.     ' this procedure tests Regex shared methods
  207.  
  208.     Sub TestSharedMethods()
  209.         ' \W means "any non-alphanumeric character."
  210.         Dim words() As String = Regex.Split("Split these words", "\W+")
  211.         Dim w As String
  212.         For Each w In words
  213.             Console.WriteLine(w)
  214.         Next
  215.         Console.WriteLine("")
  216.  
  217.         ' test the Escape method
  218.         Console.Write(Regex.Escape("(x)"))     ' => \(x\)
  219.     End Sub
  220.  
  221.     ' this procedure tests regex groups
  222.  
  223.     Sub TestGroups()
  224.         ' A regex that searches for variable assignments.
  225.         ' (Note that there are two named and two unnamed groups.)
  226.         Dim re As New Regex("(\s*)(?<name>\w+)\s*=\s*(?<value>\d+)(.*)")
  227.  
  228.         ' get the names of all groups
  229.         Dim s As String
  230.         For Each s In re.GetGroupNames
  231.             Console.Write(s & " ")     ' => 0 1 2 name value
  232.         Next
  233.         Console.WriteLine("")
  234.  
  235.         ' the GetGroupNumbers (not really interesting)
  236.         Dim n As Integer
  237.         For Each n In re.GetGroupNumbers
  238.             Console.Write(n.ToString & " ")     ' => 0 1 2 3 4
  239.         Next
  240.         Console.WriteLine("")
  241.  
  242.         Console.WriteLine(re.GroupNameFromNumber(2))    ' => 2
  243.         Console.WriteLine(re.GroupNameFromNumber(3))    ' => name
  244.  
  245.         Console.WriteLine(re.GroupNumberFromName("name"))  ' => 3
  246.         Console.WriteLine(re.GroupNumberFromName("foo"))   ' => -1
  247.     End Sub
  248.  
  249.     ' this procedure tests the Match object
  250.  
  251.     Sub TestMatch()
  252.         Dim source As String = "A sentence with five words"
  253.         Dim re As New Regex("\w+")
  254.  
  255.         ' Find the first match.
  256.         Dim m As Match = re.Match(source)
  257.         ' Enter the following loop only if the search was successful.
  258.         Do While m.Success
  259.             Console.WriteLine("{0} (found at {1})", m.Value, m.Index)
  260.             ' Find the next match; exit if not successful.
  261.             m = m.NextMatch
  262.         Loop
  263.         Console.WriteLine("")
  264.  
  265.         ' looks for sequences of zero or more digits
  266.         re = New Regex("\d*")
  267.         For Each m In re.Matches("1a23bc456de789")
  268.             ' The output from this loop shows that some matches are empty.
  269.             Console.Write(m.Value & ",")  ' => 1,,23,,456,,,789
  270.         Next
  271.         Console.WriteLine("")
  272.  
  273.         ' listing groups
  274.         source = "a = 123: b=456"
  275.         re = New Regex("(\s*)(?<name>\w+)\s*=\s*(?<value>\d+)")
  276.         For Each m In re.Matches(source)
  277.             Console.WriteLine("Variable: {0}   Value: {1}", m.Groups("name").Value, m.Groups("value").Value)
  278.             ' =>    Variable: a   Value: 123
  279.             '       Variable: b   Value: 456
  280.         Next
  281.         Console.WriteLine("")
  282.  
  283.         ' This code produces exactly the same result as the previous snippet.
  284.         For Each m In re.Matches(source)
  285.             Console.WriteLine(m.Result("Variable: ${name}   Value: ${value}"))
  286.         Next
  287.         Console.WriteLine("")
  288.     End Sub
  289.  
  290.     ' this procedure tests the Group object
  291.  
  292.     Sub TestGroupObject()
  293.         Dim source As String = "a = 123: b=456"
  294.         Dim re As New Regex("(\s*)(?<name>\w+)\s*=\s*(?<value>\d+)")
  295.  
  296.         Dim m As Match, g As Group
  297.         ' Iterate over all the matches.        
  298.         For Each m In re.Matches(source)
  299.             ' Get information on variable name
  300.             g = m.Groups("name")
  301.             Console.Write("Variable '{0}' found at index {1}", g.Value, g.Index)
  302.             ' Get information on variable value.
  303.             Console.WriteLine(", value is {0}", m.Groups("value").Value)
  304.         Next
  305.     End Sub
  306.  
  307.     ' this procedure tests the Capture object
  308.  
  309.     Sub TestCaptureObject()
  310.         Dim source As String = "abc def"
  311.         Dim re As New Regex("(\w)+")
  312.         Dim m As Match, s As String, c As Capture
  313.  
  314.         ' Get the name or numbers of all the groups.
  315.         Dim groups() As String = re.GetGroupNames
  316.  
  317.         ' Iterate over all matches.
  318.         For Each m In re.Matches(source)
  319.             ' Display information on this match.
  320.             Console.WriteLine("Match '{0}' at index {1}", m.Value, m.Index)
  321.             ' Iterate over the groups in each match.
  322.             For Each s In groups
  323.                 ' Get a reference to the corresponding group.
  324.                 Dim g As Group = m.Groups(s)
  325.                 ' Get the capture collection for this group.                
  326.                 Dim cc As CaptureCollection = g.Captures
  327.                 ' Display the number of captures.
  328.                 Console.WriteLine("  Found {0} capture(s) for group {1}", cc.Count, s)
  329.                 ' Display information on each capture.
  330.                 For Each c In cc
  331.                     Console.WriteLine("    '{0}' at index {1}", c.Value, c.Index)
  332.                 Next
  333.             Next
  334.         Next
  335.     End Sub
  336.  
  337.     ' this procedure tests the Capture object and uses it to
  338.     ' find the mantissa and exponent of numbers in fp notation
  339.  
  340.     Sub TestCaptureObject2()
  341.         Dim source As String = "11.22E33  4.55E6 "
  342.         Dim re As New Regex("((\d+).?(\d*))E(\d+)")
  343.         Dim m As Match, s As String, c As Capture
  344.  
  345.         ' Get the name or numbers of all the groups.
  346.         Dim groups() As String = re.GetGroupNames
  347.  
  348.         ' Iterate over all matches.
  349.         For Each m In re.Matches(source)
  350.             ' Display information on this match.
  351.             Console.WriteLine("Match '{0}' at index {1}", m.Value, m.Index)
  352.             ' Iterate over the groups in each match.
  353.             For Each s In groups
  354.                 ' Get a reference to the corresponding group.
  355.                 Dim g As Group = m.Groups(s)
  356.                 ' Get the capture collection for this group.                
  357.                 Dim cc As CaptureCollection = g.Captures
  358.                 ' Display the number of captures.
  359.                 Console.WriteLine("  Found {0} capture(s) for group {1}", cc.Count, s)
  360.                 ' Display information on each capture.
  361.                 For Each c In cc
  362.                     Console.WriteLine("    '{0}' at index {1}", c.Value, c.Index)
  363.                 Next
  364.             Next
  365.         Next
  366.     End Sub
  367.  
  368.     ' this procedure shows how to search for HREFs in an html file
  369.  
  370.     ' ensure that the BIN directory contains the test.htm file, or copy
  371.     ' it from the project directory if necessary
  372.  
  373.     Sub TestSearchHyperlinks()
  374.         Dim re As New Regex("<A\s+HREF\s*=\s*""?([^"" >]+)""?>(.+)</A>", RegexOptions.IgnoreCase)
  375.  
  376.         Dim source As String = FileText("test.htm")
  377.  
  378.         Dim m As Match = re.Match(source)
  379.         Do While m.Success
  380.             Console.WriteLine("{0} => {1}", m.Groups(2).Value, m.Groups(1).Value)
  381.             m = m.NextMatch()
  382.         Loop
  383.     End Sub
  384. End Module
  385.