Monday, December 31, 2007

Use RegExp to parse IP address (logfile) | VB.Net

Use Regular Expressions to parse IP address

Imports System
Imports System.Text
Imports System.Text.RegularExpressions


Public Class MainClass

Shared Sub Main()
Dim string1 As String = _
"04:03:27 127.0.0.0 www.java2s.com"

' time = one or more digits or colons
' followed by a space
' ip address = one or more digits or dots
' followed by space
' site = one or more characters
Dim regString As String = "(?<time>(\d\:)+)\s" & _
"(?<ip>(\d\.)+)\s" & _
"(?<site>\S+)"

Dim theReg As New Regex(regString)
Dim theMatches As MatchCollection = theReg.Matches(string1)

Dim theMatch As Match
For Each theMatch In theMatches
If theMatch.Length <> 0 Then
Console.WriteLine( _
"theMatch: {0}", _
theMatch.ToString( ))
Console.WriteLine( _
"time: {0}", _
theMatch.Groups("time"))
Console.WriteLine( _
"ip: {0}", _
theMatch.Groups("ip"))
Console.WriteLine( _
"site: {0}", _
theMatch.Groups("site"))
End If
Next theMatch
End Sub
End Class