VB.NET Regex, Read and Match File Lines

Use the Regex.Match method on each line of a file. Read lines with StreamReader.

Regex, file. Suppose 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.

An example. 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.

Tip: For Groups, make sure to access the group at index 1 for the first group. We do not access the first element at index 0.

VB.NET program that uses Regex on lines in file 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 Module File contents, log.txt: 2008-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.249 Output 2008-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

Notes, results. See how the part after the "Content" part of the URLs is matched. A specific part of the file names is extracted with Regex.

A summary. 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.Regex.Match
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to