VBSで正規表現を使用してテキストの文字列を置換する
普通に置換しても良いのですが、この前のエントリで正規表現を勉強したので
正規表現を使って、少し汎用的に置換出来るようにしました。
test.txtというテキストファイルに記述した「Test」という文字列を「New Test」に置換する場合
Dim objFile ' 対象ファイル Dim oldText ' 置換前テキスト Dim newText ' 置換後テキスト Dim objFSO ' ファイルシステムオブジェクト Dim objRep ' 正規表現オブジェクト Dim repText ' 置換対象文字列 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("C:\work\test.txt") ' テキストデータ読込 oldText = objFile.ReadAll ' 置換対象文字列 repText = "New Test" Set objRep = New RegExp objRep.Multiline = True ' 正規表現パターンを指定する objRep.Pattern = "T..t" objRep.IgnoreCase = True objRep.Global = True ' テキスト変換 newText = objRep.replace(oldText, repText) objFile.Close ' 書き込み Set objFile = objFSO.CreateTextFile("C:\work\test.txt") objFile.WriteLine (newText) objFile.Close msgbox "完了"
これで完成です(*´∇`*)