14.1 正则表达式概述

14.1.1 基础知识

 

代码
Imports System.Text.RegularExpressions
Module Fundamentales
    
'-----------------------------------------
    ' Regular expressions fundamentales
    '-----------------------------------------
    Sub a()
        
' This source string contains 3 groups that match the Regex.
        Dim text As String = "a1 = a1 & e2"

        
Dim re As New Regex("[aeiou]\d")

        
' Get the collection of matches.
        Dim mc As MatchCollection = re.Matches(text)

        
' How many occurrences did we find?
        Console.WriteLine("{0} matches", mc.Count) ' => 3 matches

        
For Each m As Match In mc
            
' Display text and position of this match.
            Console.WriteLine("  '{0}' at position {1}", m.Value, m.Index)
        
Next
    
End Sub

    
' Replacing a substring Search for the "a" character followed by a digit.
    Sub b()
        
Dim text As String = "a1 = a1 & e2"
        
Dim re2 As New Regex("a\d")
        
' Drop the digit that follows the "a" character.
        Dim res As String = re2.Replace(text, "a"' => a = a & e2
        Console.WriteLine("Result of replacement: {0}", res)
    
End Sub

    
'This code snippet is equivalent to the previous one,
    'but it doesn't instantiate a Regex object.
    Sub c()
        
Dim text As String = "a1 = a1 & e2"
        res 
= Regex.Replace(text, "a\d""a")
    
End Sub
End Module

 

 

14.1.2 正则表达式语言

14.1.3 正则表达式选项

 

代码
Imports System.Text.RegularExpressions
Imports System.IO

Module Module2
    
Sub a()
        
Dim source As String = "ABC Abc abc"
        
Dim mc As MatchCollection = Regex.Matches(source, "abc")
        Console.WriteLine(mc.Count) 
' => 1

        mc 
= Regex.Matches(source, "abc", RegexOptions.IgnoreCase)
        Console.WriteLine(mc.Count) 
' => 3

        Console.WriteLine()
    
End Sub

    
' Create a compiled regular expression that searches 
    ' words that start with uppercase or lowercase A.
    Sub b()
        
Dim reComp As New Regex("\Aw+", RegexOptions.IgnoreCase Or RegexOptions.Compiled)
    
End Sub

    
Sub c()
        
' Match a string optionally enclosed in single or double quotation marks.
        Dim pattern As String =
                
"\s*         # ignore leading spaces" + vbCrLf &
                
"(           # two cases: quoted or unquoted string" + vbCrLf &
                
"(?<quote>   # case 1: define a group named 'quote' '" + vbCrLf &
                
"['""])     # the group is single or a double quote" + vbCrLf &
                
".*?         # a sequence of characters (lazy matching)" + vbCrLf &
                
"\k<quote>   # followed by the same quote char" + vbCrLf &
                
"|           # end of case 1" + vbCrLf &
                
"[^'""]+     # case 2: a string without quotes" + vbCrLf &
                
")           # end of case 2" + vbCrLf &
                
"\s*         # ignore trailing spaces"

        
Dim re As New Regex(pattern, RegexOptions.IgnorePatternWhitespace)

        
Dim source As String = "one 'two three' four ""five six"" seven"
        
For Each m As Match In re.Matches(source)
            Console.WriteLine(
"[{0}]", m.Value)
        
Next
        Debug.Assert(re.Matches(source).Count 
= 5)
    
End Sub

    
' Compile this application and create FileGrep.Exe executable.
    Sub Main(ByVal args() As String)
        
' Show syntax if too few arguments.
        If args.Length <> 2 Then
            Console.WriteLine(
"Syntax: FILEGREP ""regex"" filespec")
            
Exit Sub
        
End If

        
Dim pattern As String = args(0)
        
Dim filespec As String = args(1)
        
' Create the regular expression (throws if pattern is invalid).
        Dim filePattern As New Regex(pattern, RegexOptions.IgnoreCase Or RegexOptions.Multiline)

        
' Apply the regular expression to each file in specified or current directory.
        Dim dirname As String = Path.GetDirectoryName(filespec)
        
If dirname.Length = 0 Then dirname = Directory.GetCurrentDirectory
        
Dim search As String = Path.GetFileName(filespec)
        
For Each fname As String In Directory.GetFiles(dirname, search)
            
' Read file contents and apply the regular expression to it.
            Dim text As String = File.ReadAllText(fname)
            
Dim mc As MatchCollection = filePattern.Matches(text)
            
' Display file name if one or more matches.
            If mc.Count > 0 Then
                Console.WriteLine(
"{0} [{1} matches]", fname, mc.Count)
            
End If
        
Next
    
End Sub

    
Sub d()
        
' Change directory so that project directory becomes current.
        Directory.SetCurrentDirectory(Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory)))

        
' The pattern matches from the keyword to the end of the line.
        Dim pattern As String = "(?im)^\s+(dim|public|private) \w+ As .+(?=\r\n)"
        
Dim source As String = File.ReadAllText("Module1.vb")
        
Dim mc As MatchCollection = Regex.Matches(source, pattern)
        
For Each m As Match In mc
            Console.WriteLine(m.Value)
        
Next
    
End Sub
End Module

 

 14.2 正则表达式类型

14.2.1 Regex 类型

 

代码
Imports System.Text.RegularExpressions
Imports System.IO
Imports System.Globalization

Module Module3
    
Sub a()
        
'this regex object can search the word "dim" in a case insensitive way.
        Dim re As New Regex("\bdim\b", RegexOptions.IgnoreCase)
    
End Sub

    
Sub b(ByVal re As Regex, ByVal source As String)
        
Dim mc As MatchCollection = re.Matches(source)

        
For Each m As Match In re.Matches(source, 100)
            Console.WriteLine(m.ToString)
        
Next
    
End Sub
    
Sub c()
        
' Finds consecutive groups of space-delimited numbers.
        Dim re As New Regex("\G\s*\d+")
        
' Note that search stops at the first non-numeric group.
        Console.WriteLine(re.Matches("12 34 56 ab 78").Count)     ' => 3
    End Sub

    
Sub d()
        
' Check whether the input string is a date in the format mm-dd-yy or 
        ' mm-dd-yyyy. (The source string can use slashes as date separators and 
        ' can contain leading or trailing white spaces.)
        Dim re2 As New Regex("^\s*\d{1,2}(/|-)\d{1,2}\1(\d{4}|\d{2})\s*$")

        
If re2.IsMatch(" 12/10/2001  "Then
            Console.WriteLine(
"The date is formatted correctly.")
            
' (We don't check whether month and day values are in valid range.)
        End If
    
End Sub

    
Sub MatchesLazyEvaluation()
        
' Prepare to search for the "A" character.
        Dim re As New Regex("A")

        
' Create a very long string with a match at its beginning and its end.
        Dim text As String = "A" & New String(" "c, 1000000& "A"

        
Dim sw As New Stopwatch()
        sw.Start()
        
For Each m As Match In re.Matches(text)
            
' Show how long it took to find this match.
            Console.WriteLine("Elapsed {0} milliseconds", sw.ElapsedMilliseconds)
        
Next
        sw.Stop()
    
End Sub

    
Sub TheMatchMethod()
        
' Search all the dates in a source string.
        Dim source As String = " 12-2-1999  10/23/2001 4/5/2001 "
        
Dim re As New Regex("\s*\d{1,2}(/|-)\d{1,2}\1(\d{4}|\d{2})")
        
' Find the first match.
        Dim m As Match = re.Match(source)
        
' Enter the following loop only if the search was successful.
        Do While m.Success
            
' Display the match, but discard leading and trailing spaces.
            Console.WriteLine(m.ToString.Trim())
            
' Find the next match; exit if not successful.
            m = m.NextMatch()
        
Loop
    
End Sub

    
Sub TheSplitMethod()
        
Dim source As String = "123, 456,,789"
        
Dim re As New Regex("\s*,\s*")
        
For Each s As String In re.Split(source)
            
' Note that the third element is a null string.
            Console.Write(s & "-")              ' => 123-456--789-
        Next
        Console.WriteLine()

        
Dim arr() As String = re.Split(source, 5)
        
Dim arr2() As String = re.Split(source, 5100)
    
End Sub

    
Sub TheReplaceMethod()
        
Dim source As String = "12-2-1999  10/23/2001  4/5/2001 "
        
Dim pattern As String =
            
"\b(?<mm>\d{1,2})(?<sep>(/|-))(?<dd>\d{1,2})\k<sep>(?<yy>(\d{4}|\d{2}))\b"
        
Dim re As New Regex(pattern)
        Console.WriteLine(
            re.Replace(source, 
"${dd}${sep}${mm}${sep}${yy}")
            ) 
' => 2-12-1999  23/10/2001  5/4/2001
        Debug.Assert(re.Replace(source, "${dd}${sep}${mm}${sep}${yy}"= "2-12-1999  23/10/2001  5/4/2001 ")

    
End Sub

    
Sub TheReplaceMethod2()
        
' Expand all "ms" abbreviations to "Microsoft" (regardless of their case).
        Dim text As String = "Welcome to ms Ms ms MS"
        
Dim re2 As New Regex("\bMS\b", RegexOptions.IgnoreCase)

        
' Replace up to two occurrences, starting at the 12-th character.
        Console.WriteLine(
            re2.Replace(text, 
"Microsoft"212)
            ) 
' => Welcome to ms Microsoft Microsoft MS
    End Sub

    
Sub TestReplaceWithCallback()
        
' This pattern defines two integers separated by a plus sign.
        Dim re As New Regex("\d+\s*\+\s*\d+")
        
Dim source As String = "a = 100 + 234: b = 200+345"
        
' Replace all sum operations with their results.
        Console.WriteLine(
            re.Replace(source, 
AddressOf DoSum)
            ) 
' => a = 334: b = 545
    End Sub

    
Private Function DoSum(ByVal m As Match) As String
        
' Parse the two operands.
        Dim args() As String = m.Value.Split("+"c)
        
Dim n1 As Long = CLng(args(0))
        
Dim n2 As Long = CLng(args(1))
        
' Return their sum, as a string.
        Return (n1 + n2).ToString()
    
End Function

    
Private Function ConvertToUpperCase(ByVal m As Match) As String
        
Return m.Value.ToUpper()
    
End Function

    
Private Function ConvertToLowerCase(ByVal m As Match) As String
        
Return m.Value.ToLower()
    
End Function

    
Private Function ConvertToProperCase(ByVal m As Match) As String
        
' We must convert to lowercase first, to ensure that ToTitleCase works as intended.
        Return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(m.Value.ToLower())
    
End Function

    
Sub TestReplaceWithCallback2()
        
' Convert country names in the text string to uppercase.
        Dim text As String = "I visited italy, france, and then GERMANY"
        
Dim re2 As New Regex("\b(Usa|France|Germany|Italy|Great Britain)\b", RegexOptions.IgnoreCase)
        text 
= re2.Replace(text, AddressOf ConvertToProperCase)
        Console.WriteLine(text)     
' => I visited Italy, France, and then Germany
    End Sub

    
Sub StaticMethods1()
        
' \W means "any nonalphanumeric character."
        Dim words() As String = Regex.Split("Split these words""\W+")
        Console.WriteLine(
"{0} words", words.Length)
        Console.WriteLine()
    
End Sub

    
Sub EscapeMethod1()
        
' The Escape method
        Console.WriteLine(Regex.Escape("(x)")) ' => \(x\)
    End Sub

    
Sub EscapeMethod2(ByVal source As StringByVal txtChars As System.Windows.Forms.TextBox)
        
If Regex.IsMatch(source, Regex.Escape(txtChars.Text)) Then
        
End If
    
End Sub

    
' The Unescape method
    Sub StaticMethods(ByVal s As String)
        s 
= Regex.Unescape("First line\r\nSecond line ends with null char\x00")
        Console.WriteLine(s)
    
End Sub
End Module

 

14.2.2 MatchCollection和Match类型

 

代码
Imports System.IO
Imports System.Text.RegularExpressions

Module Module4
    
Sub a()
        
Dim re As New Regex("\d*")
        
For Each m As Match In re.Matches("1a23bc456de789")
            
' The output from this loop shows that some matches are empty.
            Console.Write(m.Value & ",")  ' => 1,,23,,456,,,789,,
        Next
    
End Sub

    
Sub TestGroups()
        
Dim source As String = "a = 123: b=456"
        
Dim re2 As New Regex("(\s*)(?<name>\w+)\s*=\s*(?<value>\d+)")
        
For Each m As Match In re2.Matches(source)
            Console.WriteLine(
"Variable: {0}, Value: {1}",
                              m.Groups(
"name").Value,
                              m.Groups(
"value").Value)
        
Next
    
End Sub

    
Sub TestResult(ByVal re2 As Regex, ByVal source As String)
        
' This code produces exactly the same result as the preceding snippet.
        For Each m As Match In re2.Matches(source)
            Console.WriteLine(m.Result(
"Variable: ${name}, Value: ${value}"))
        
Next
    
End Sub
End Module

 

 

14.2.3 Group类型

 

代码
Imports System.Text.RegularExpressions
Imports System.IO

Module Module5
    
Sub TheGroupType()
        
Dim text As String = "a = 123: b=456"
        
Dim re As New Regex("(\s*)(?<name>\w+)\s*=\s*(?<value>\d+)")
        
For Each m As Match In re.Matches(text)
            
Dim g As Group = m.Groups("name")
            
' Get information on variable name and value.
            Console.Write("Variable '{0}' found at index {1}", g.Value, g.Index)
            Console.WriteLine(
", value is {0}", m.Groups("value").Value)
        
Next
    
End Sub

    
Sub ParseHtmlFile()
        
Dim re As New Regex("<A\s+HREF\s*=\s*("".+?""|.+?)>(.+?)</A>", RegexOptions.IgnoreCase)
        
' Load the contents of an HTML file.
        Dim text As String = File.ReadAllText("test.htm")

        
' Display all occurrences.
        Dim m As Match = re.Match(text)
        
Do While m.Success
            Console.WriteLine(
"{0} => {1}", m.Groups(2).Value, m.Groups(1).Value)
            m 
= m.NextMatch()
        
Loop
    
End Sub
End Module

 

 

14.2.4 CaptureCollection和Capture类型

 

代码
    Sub TheCaptureCollection()
        
Dim text As String = "abc def"
        
Dim re As New Regex("(\w)+")
        
' Get the name or numbers of all the groups.
        Dim groups() As String = re.GetGroupNames()

        
' Iterate over all matches.
        For Each m As Match In re.Matches(text)
            
' Display information on this match.
            Console.WriteLine("Match '{0}' at index {1}", m.Value, m.Index)
            
' Iterate over the groups in each match.
            For Each s As String In groups
                
' Get a reference to the corresponding group.
                Dim g As Group = m.Groups(s)
                
' Get the capture collection for this group.
                Dim cc As CaptureCollection = g.Captures
                
' Display the number of captures.
                Console.WriteLine("  Found {0} capture(s) for group {1}", cc.Count, s)
                
' Display information on each capture.
                For Each c As Capture In cc
                    Console.WriteLine(
"    '{0}' at index {1}", c.Value, c.Index)
                
Next
            
Next
        
Next
    
End Sub

 

 14.3.2 查找单词和带引号的字符串

 

代码
Imports System.Text.RegularExpressions
Imports System.IO

Module Regularexpressionsatwork
    
' This pattern includes words with accented characters and numbers.
    Sub a()
        
Dim text As String = "A word with accented vowels, and the 123 number."
        
Dim pattern As String = "\w+"

        
For Each m As Match In Regex.Matches(text, pattern)
            Console.WriteLine(m.Value)
        
Next
    
End Sub

    
' This pattern doesn't consider words with accented chars.
    Sub b(ByVal text As String)
        
Dim pattern As String = "[A-Za-z]+"
        
For Each m As Match In Regex.Matches(text, pattern)
            Console.WriteLine(m.Value)
        
Next
    
End Sub

    
' This pattern works correctly and uses Unicode character classes.
    Sub c(ByVal text As String)
        
Dim pattern As String = "(\p{Lu}|\p{Ll})+"
        
For Each m As Match In Regex.Matches(text, pattern)
            Console.WriteLine(m.Value)
        
Next
    
End Sub

    
' This pattern works correctly and uses character subtraction.
    Sub d(ByVal text As String)
        
Dim pattern As String = "[\w-[0-9_]]+"
        
For Each m As Match In Regex.Matches(text, pattern)
            Console.WriteLine(m.Value)
        
Next
    
End Sub

    
' Eliminating noise words.
    Sub NoiseWords()
        
Dim pattern As String = "\b(?!(the|a|an|and|or|on|of|with)\b)\w+"
        
Dim text As String = "A fox and another animal on the lawn"
        
For Each m As Match In Regex.Matches(text, pattern, RegexOptions.IgnoreCase)
            Console.Write(
"{0} ", m.Value)     ' => fox another animal lawn
        Next
    
End Sub

    
Sub QuotedStrings()
        
Dim text As String = "one 'two three' four ""five six"" seven"
        
Dim pattern As String = "((?<q>[""']).*?\k<q>|\w+)"
        
Dim re As New Regex(pattern)
        
For Each m As Match In re.Matches(text)
            Console.WriteLine(
"{0}", m.Value)
        
Next
    
End Sub

    
Sub UniqueWordsByHashTable()
        
Dim text As String = "one two three two zone four three"

        
Dim re As New Regex("\w+")
        
Dim words As New Hashtable()
        
For Each m As Match In re.Matches(text)
            
If Not words.Contains(m.Value) Then
                Console.Write(
"{0} ", m.Value)
                words.Add(m.Value, 
Nothing)
            
End If
        
Next
    
End Sub

    
Sub UniqueWordsByRegex(ByVal text As String)
        
Dim pattern As String = "(?<word>\b\w+\b)(?!.+\b\k<word>\b)"
        
For Each m As Match In Regex.Matches(text, pattern)
            Console.Write(
"{0} ", m.Value)
        
Next
    
End Sub

    
Sub DuplicatedWords()
        
Dim text As String = "one two three two zone four three"
        
Dim pattern As String = "(?<word>\b\w+\b)(?=.+\b\k<word>\b)"

        
For Each m As Match In Regex.Matches(text, pattern)
            Console.Write(
"{0} ", m.Value)
        
Next
    
End Sub

    
Sub ProximitySearches()
        
Dim text As String = "one two three two zone four three"
        
Dim pattern As String = "\bone(\W+\w+){0,4}\W+\bfour\b"

        
For Each m As Match In Regex.Matches(text, pattern)
            Console.Write(
"{0} ", m.Value)
        
Next
    
End Sub

    
Sub TestProximityMatches(ByVal text As String)
        
Dim mc As MatchCollection = ProximityMatches(Text, "one""four"4)
        
If mc.Count > 0 Then
            Console.WriteLine(
"Found: {0}", mc(0).Value)
        
End If
    
End Sub
    
Function ProximityMatches(ByVal text As String,
                              
ByVal word1 As String,
                              
ByVal word2 As String,
                              
ByVal maxDistance As IntegerAs MatchCollection
        
Dim pattern As String =
            
"\b" & word1 & "(\W+\w+){0," & maxDistance.ToString() & "}\" & "W+\b" & word2 & "\b"
        
Dim re As New Regex(pattern, RegexOptions.IgnoreCase)
        
Return re.Matches(text)
    
End Function
End Module

 

 14.3.3 验证字符串、数字和日期

 

代码
Imports System.Text.RegularExpressions

Module Validating
    
Sub CheckUSZipCode()
        
Dim pattern As String = "^(?!00000)\d{5}$"

        
Dim text As String = "12345"
        
If Regex.IsMatch(text, pattern) Then
            
' It's a string containing 5 digits.
            Console.WriteLine("{0} is a valid US zip code", text)
        
Else
            Console.WriteLine(
"{0} isn't a valid US zip code", text)
        
End If

        text 
= "00000"
        
If Regex.IsMatch(text, pattern) Then
            
' It's a string containing 5 digits.
            Console.WriteLine("{0} is a valid US zip code", text)
        
Else
            Console.WriteLine(
"{0} isn't a valid US zip code", text)
        
End If
    
End Sub

    
Sub CheckPasswordPolicy()
        
'至少8个字符,其中要包含数字和大写,小写字母的组合
        Dim pattern As String = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$"

        
Dim text As String = "foobar12AK"
        
If Regex.IsMatch(text, pattern) Then
            
' It's a string containing 5 digits.
            Console.WriteLine("{0} is a robust password", text)
        
Else
            Console.WriteLine(
"{0} isn't a robust password", text)
        
End If

        text 
= "foobar12"
        
If Regex.IsMatch(text, pattern) Then
            
' It's a string containing 5 digits.
            Console.WriteLine("{0} is a robust password", text)
        
Else
            Console.WriteLine(
"{0} isn't a robust password", text)
        
End If
    
End Sub

    
Sub ValidateIntegerRanges1()
        
' Validate an integer in the range 1 to 9999, reject leading zeroes.
        Dim pattern As String = "^(?!0)\d{1,4}$"
        
For Each text As String In New String() {"123""0123""0""10000"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a number in the range 1-9999, with no leading zeroes", text)
            
Else
                Console.WriteLine(
"{0} isn't a number in the range 1-9999, with no leading zeroes", text)
            
End If
        
Next
    
End Sub
    
Sub ValidateIntegerRanges2()
        
' Validate an integer in the range 0 to 9999, but reject leading zeroes.
        Dim pattern As String = "^(0|(?!0)\d{1,4})$"
        
For Each text As String In New String() {"123""0123""0""10000"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a number in the range 0-9999, with no leading zeroes", text)
            
Else
                Console.WriteLine(
"{0} isn't a number in the range 0-9999, with no leading zeroes", text)
            
End If
        
Next
    
End Sub

    
Sub ValidateIntegerRanges3()
        
' Validate an integer in the range 0 to 255, with no leading zeroes
        Dim pattern As String = "^(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$"
        
For Each text As String In New String() {"0""8""23""123""255""256""300""012"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a number in the range 0-255", text)
            
Else
                Console.WriteLine(
"{0} isn't a number in the range 0-255", text)
            
End If
        
Next
    
End Sub

    
Sub ValidateIntegerRanges4()
        
' Validate a 4-part IP address
        Dim pattern As String = "^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$"
        
For Each text As String In New String() {"0.0.0.1""12.23.45.255""1.2.3""2.4.6.256"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a valid IP address", text)
            
Else
                Console.WriteLine(
"{0} isn't a valid IP address", text)
            
End If
        
Next
    
End Sub

    
Sub ValidateIntegerRanges5()
        
' Validate an integer number in the range 0 to 65535; leading zeroes are OK.
        Dim pattern As String = "^([1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-4]|\d{1,4})$"
        
For Each text As String In New String() {"0""4""23""345""1234""23456""54567""65536""73456""-123"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is an integer in the range 0-65535", text)
            
Else
                Console.WriteLine(
"{0} isn't an integer in the range 0-65535", text)
            
End If
        
Next
    
End Sub

    
Sub ValidateIntegerRanges()
        
' Validate an integer in the range -32768 to 32767; leading zeroes are OK.
        Dim pattern As String = "^(-?[12]\d{4}|-?3[0-1]\d{3}|-?32[0-6]\d{2}|-?327[0-5]\d|" _
           
& "-?3276[0-7]|-32768|-?\d{1,4})$"
        
For Each text As String In New String() {"-4""-123""0""4""23""345""1234""23456""32767""32768""54567""-32768""-32800"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is an integer in the range -32768 to 32767", text)
            
Else
                Console.WriteLine(
"{0} isn't an integer in the range -32768 to 32767", text)
            
End If
        
Next
    
End Sub

    
Sub ValidatingTimes()
        
' Validate a time value in the format hh:mm; the hour number can have a leading zero.
        Dim pattern As String = "^(2[0-3]|[01]\d|\d):[0-5]\d$"
        
For Each text As String In New String() {"0:00""1:23""3:333""12:4""12:12""23:00""23:59""23:61""24:00"}
            
If Regex.IsMatch(text, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a valid time value", text)
            
Else
                Console.WriteLine(
"{0} isn't a valid time value", text)
            
End If
        
Next
    
End Sub

    
Sub ValidatingDates()
        
' This portion deals with months with 31 days.
        Dim p1 As String = "(0?[13578]|10|12)/(3[01]|[012]\d|\d)/\d{2}"
        
' This portion deals with months with 30 days.
        Dim p2 As String = "(0?[469]|11)/(30|[012]\d|\d)/\d{2}"
        
' This portion deals with February 29 in leap years.
        Dim p3 As String = "(0?2)/29/([02468][048]|[13579][26])"
        
' This portion deals with other days in February.
        Dim p4 As String = "(0?2)/(2[0-8]|[01]\d|\d)/\d{2}"
        
' Put all the patterns together.
        Dim pattern As String = String.Format("^({0}|{1}|{2}|{3})$", p1, p2, p3, p4)
        
' Check the date.

        
For Each txt In New String() {"1/1/99""11/30/99""11/31/99""1/32/90""2/28/03""2/29/03""2/29/04"}
            
If Regex.IsMatch(txt, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a valid date in mm/dd/yy format", txt)
            
Else
                Console.WriteLine(
"{0} isn't a valid date in mm/dd/yy format", txt)
            
End If
        
Next
    
End Sub

    
Sub ValidatingDates2()
        
' This portion deals with months with 31 days.
        Const s1 As String = "(0?[13578]|10|12)/(3[01]|[12]\d|0?[1-9])/(\d\d)?\d\d"
        
' This portion deals with months with 30 days.
        Const s2 As String = "(0?[469]|11)/(30|[12]\d|0?[1-9])/(\d\d)?\d\d "
        
' This portion deals with days 1-28 in February in all years.
        Const s3 As String = "(0?2)/(2[0-8]|[01]\d|0?[1-9])/(\d\d)?\d\d"
        
' This portion deals with February 29 in years divisible by 400.
        Const s4 As String = "(0?2)/29/(1600|2000|2400|2800|00)"
        
' This portion deals with February 29 in non-century leap years.
        Const s5 As String = "(0?2)/29/(\d\d)?(0[48]|[2468][048]|[13579][26])"
        
' Put all the patterns together.
        Dim pattern As String = String.Format("^({0}|{1}|{2}|{3}|{4})$", s1, s2, s3, s4, s5)

        
For Each txt In New String() {"1/1/2001""11/30/99""11/31/1999""1/32/2001""2/28/2003""2/29/2003""2/29/2004""2/29/2000""2/29/2100"}
            
If Regex.IsMatch(txt, pattern) Then
                
' It's a string containing 5 digits.
                Console.WriteLine("{0} is a valid date in mm/dd/yyyy format", txt)
            
Else
                Console.WriteLine(
"{0} isn't a valid date in mm/dd/yyyy format", txt)
            
End If
        
Next
    
End Sub

End Module

 

 

14.3.4 查找嵌套标记

 

14.3.5 分析数据文件

 

14.3.6 分析和计算表达式

 

14.3.7 分析代码

 

14.3.8 使用正则表达式