Leverage Regular Expressions (Continued)
Search for Date Values
This example shows how you can search for date values in the m/d/yyyy format (where month and day numbers may have one or two digits) anywhere in the source text:
Dim re As New _
Regex("\b1?\d/[123]?\d/\d{4}\b")
Dim m As Match
For Each m In re.Matches(text)
Console.WriteLine(m.Value)
Next
The | and ( ) constructs let you specify alternative matching strings. This code uses them to find variable declarations in a VB source file. (For simplicity's sake, it assumes the variable's type doesn't contain dots.) Notice the IgnoreCase option for performing case-insensitive searches:
Dim pattern As String = _
"\b(Dim|Private|Public)\s+\w+" & _
"\s+As\s+\w+"
Dim re As New Regex(pattern, _
RegexOptions.Multiline Or _
RegexOptions.IgnoreCase)
Dim m As Match
' source is the VB code to parse
For Each m In re.Matches(source)
Console.WriteLine(m.Value)
Next
The ( ) construct is also useful for applying quantifiers to a subsequence of characters. For example, you can modify the previous search pattern to account for the optional New keyword in variable declarations:
Dim pattern As String = _
"\b(Dim|Private|Public)\s+\w+" & _
"\s+As\s+(New\s+)?\w+"
Interestingly, the ( ) construct defines implicitly a numbered matching group—that is, a subsequence in the found string. Groups are numbered starting with 1 and let you refer to portions of the match. You can use groups to improve the search for variable declarations in a VB listing:
Dim pattern As String = "\b" & _
"(Dim|Private|Public)\s+(\w+)" & _
"\s+As\s+(New\s+)?(\w+)"
Back to top
|