Regex
, fileSuppose we have a file, like a server log file, and want to read in each line and match a part of the line. The Regex.Match
method, and StreamReader
, can be used.
With a While
-loop, we can enumerate each line in the file. Then we extract matching parts with the Groups property on the Match
. This returns a string
value.
Here we have a log file, contained in log.txt, and we access this in the StreamReader
when we create it. We create a Regex
that matches a certain URL pattern.
Imports System.IO Imports System.Text.RegularExpressions Module Module1 Sub Main() ' Create Regex. Dim regex As Regex = New Regex("\s/Content/([a-zA-Z0-9\-]+?)\.aspx") ' Loop over the lines in this text file. Using reader As StreamReader = New StreamReader("C:\programs\log.txt") While (True) Dim line As String = reader.ReadLine() ' End if Nothing. If line = Nothing Then Return End If ' Try to match. Dim match As Match = regex.Match(line) If match.Success Then ' Get first group and print it. Dim value As String = match.Groups(1).Value Console.WriteLine(line) Console.WriteLine("... " + value) End If End While End Using End Sub End Module2008-10-16 23:56:44 W3SVC2915713 GET /Content/String.aspx - 80 66.249 2008-10-16 23:59:50 W3SVC2915713 GET /Content/Trim-String-Regex.aspx - 80 66.2492008-10-16 23:56:44 W3SVC2915713 GET /Content/String.aspx - 80 66.249 ... String 2008-10-16 23:59:50 W3SVC2915713 GET /Content/Trim-String-Regex.aspx - 80 66.249 ... Trim-String-Regex
See how the part after the "Content" part of the URLs is matched. A specific part of the file names is extracted with Regex
.
Regex
is often used with StreamReader
to match each line in a file. Parts of each line can be extracted and stored in the remainder of the VB.NET program.