Home
Map
Regex, Read and Match File LinesUse the Regex.Match method on each line of a file. Read lines with StreamReader.
VB.NET
This page was last reviewed on Dec 21, 2022.
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.
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
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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.