元ネタはこちらですhttp://q.hatena.ne.jp/1362164889
文字を置換してくれるプログラムがあるのですが
こちらに別の置換条件を追加させる場合どうすればいいのでしょうか?教えてください。
Dim objFile ' 対象ファイル
Dim oldText ' 置換前テキスト
Dim newText ' 置換後テキスト
Dim objFSO ' ファイルシステムオブジェクト
Dim objRep ' 正規表現オブジェクト
Dim repText ' 置換後文字列
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("hoge.txt")
oldText = objFile.ReadAll
repText = "1"
Set objRep = New RegExp
objRep.Multiline = True
objRep.Pattern = "a\n"
newText = objRep.replace(oldText, repText)
objFile.Close
Set objFile = objFSO.CreateTextFile("aab.txt")
objFile.WriteLine (newText)
objFile.Close
とりあえず3つにしてみました。
Dim objFile ' 対象ファイル Dim oldText ' 置換前テキスト Dim newText ' 置換後テキスト Dim objFSO ' ファイルシステムオブジェクト Dim objRep ' 正規表現オブジェクト Dim repText ' 置換後文字列 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("hoge.txt") oldText = objFile.ReadAll ' オブジェクトの準備とパラメータ設定 Set objRep = New RegExp objRep.Multiline = True objRep.Global = True ' 置換条件の設定と置換実行(1) objRep.Pattern = "a\n" repText = "1" newText = objRep.replace(oldText, repText) ' 置換条件の設定と置換実行(2) objRep.Pattern = "b\n" repText = "2" newText = objRep.replace(newText, repText) ' 置換条件の設定と置換実行(3) objRep.Pattern = "c\n" repText = "3" newText = objRep.replace(newText, repText) objFile.Close Set objFile = objFSO.CreateTextFile("aab.txt") objFile.WriteLine (newText) objFile.Close
下記も参考にして置換で必要な手続き順序を学習してみてください。
http://q.hatena.ne.jp/1362838683#a1193082
とりあえず3つにしてみました。
Dim objFile ' 対象ファイル Dim oldText ' 置換前テキスト Dim newText ' 置換後テキスト Dim objFSO ' ファイルシステムオブジェクト Dim objRep ' 正規表現オブジェクト Dim repText ' 置換後文字列 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("hoge.txt") oldText = objFile.ReadAll ' オブジェクトの準備とパラメータ設定 Set objRep = New RegExp objRep.Multiline = True objRep.Global = True ' 置換条件の設定と置換実行(1) objRep.Pattern = "a\n" repText = "1" newText = objRep.replace(oldText, repText) ' 置換条件の設定と置換実行(2) objRep.Pattern = "b\n" repText = "2" newText = objRep.replace(newText, repText) ' 置換条件の設定と置換実行(3) objRep.Pattern = "c\n" repText = "3" newText = objRep.replace(newText, repText) objFile.Close Set objFile = objFSO.CreateTextFile("aab.txt") objFile.WriteLine (newText) objFile.Close
下記も参考にして置換で必要な手続き順序を学習してみてください。
http://q.hatena.ne.jp/1362838683#a1193082
改行コードは質問文どおりに¥nにしてますが、
対象ファイルによっては¥r¥nに替えるなどしてください。
objRep.Global = True の行が抜けていましたので回答に追加修正しました。
置換の指定ですが
repText = "1"
objRep.Pattern = "a\n"
newText = objRep.replace(oldText, repText)
で セットになります。
この場合だと oldTextの内容を objRep.Patternの検索条件で repText に置き換えてnewText にセットするということです。
つまり、置換条件を追加する場合は、この置換処理を追加してやればいいだけです。
あと、置換元の変数も 置換したものに 変えたほうがいいですね。
これを理解すれば いくらでも追加できるでしょう。
改行コードは質問文どおりに¥nにしてますが、
2013/03/11 16:44:10対象ファイルによっては¥r¥nに替えるなどしてください。
objRep.Global = True の行が抜けていましたので回答に追加修正しました。
2013/03/12 17:50:48