正規表現

Last-modified: 2011-08-15 (月) 02:00:12
amazon.gif

テキストからIPアドレスを抜き出す。

テキストの中身

[L 2008 05 12 14:21] 00001 tsi cntr User from 10.0.0.61 logged in
[L 2008 05 12 14:21] 00001 tsi cntr User from 10.0.0.61 logged out
[L 2008 05 12 14:22] 00002 gyro cntr User from 10.0.0.61 logged in
[L 2008 05 12 14:22] 00002 gyro cntr User from 10.0.0.61 logged out
[L 2008 05 12 14:24] 00003 kensnxway cntr User from 10.0.0.61 logged in
[L 2008 05 12 14:24] 00003 kensnxway cntr User from 10.0.0.61 logged out

サンプルプログラム

Imports System.text
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub btnNukidasi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNukidasi.Click
        Dim Tx As String = ""
       Dim Wx As String = ""
       Dim Fname1 As String = ""
       Dim CsvFname As String = ""
       Dim Sw As IO.StreamWriter
       Dim Sr As IO.StreamReader
       Dim r As Regex
       Dim m As Match
       If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
           Fname1 = Me.OpenFileDialog1.FileName
       End If
       If IO.File.Exists(Fname1) = False Then
           MessageBox.Show("該当ファイルなし!")
           Exit Sub
       End If
       ' 出力ファイル セット
       CsvFname = System.IO.Path.GetDirectoryName(Fname1) & "\11.CSV"
       If IO.File.Exists(CsvFname) = True Then
           IO.File.Delete(CsvFname)
       End If
       Sw = New IO.StreamWriter(CsvFname, False, System.Text.Encoding.Default)
       Sw.WriteLine("日付,IP")
       '読込みファイル セット
       Sr = New IO.StreamReader(Fname1, System.Text.Encoding.Default)
       Tx = Sr.ReadLine
       Do While Not Tx Is Nothing
           ' 日時 取出し
           If Strings.InStr(Tx, "]") > 0 Then
               Wx = MidB(Tx, 1, Strings.InStr(Tx, "]")) '& ","
               Tx = Tx.Replace(Wx, "") ']以前の文字列を切る( 置き換え )
               Tx = Tx.Trim
               Wx = MidB(Wx, 4, 16) & ","
           End If
           r = New Regex("([0-9]{1,3})\S([0-9]{1,3})\S([0-9]{1,3})\S([0-9]{1,3})\d")
           m = r.Match(Tx)
           While m.Success
               Wx &= m.Value
               m = m.NextMatch
               Sw.WriteLine(Wx)
           End While
           Tx = Sr.ReadLine
       Loop
       Sw.Close()
       Sr.Close()
       MessageBox.Show("Fin!")
   End Sub
End Class

参考

http://msdn.microsoft.com/ja-jp/library/c75he57e%28v=VS.80%29.aspx
http://dobon.net/vb/dotnet/string/regexmatch.html

サイト内リンク

OS系

Office系

その他