[英]Search and replace text file content using MS-Word VBA Regex
我目前正在使用下面的代碼(感謝 Maco)來替換多個文本文件而不打開並手動替換它們。 它工作得很好,但我希望它能夠替換一些東西,例如,有時內容包含錯誤,比如:
例題
化
我只想刪除行尾的輸入標記和破折號,以便“exemtion”這個詞是正確的。 Notepad ++中的一個簡單宏可以輕松完成,但是您必須手動打開每個文件才能做到這一點,對於數百個文件來說效率不高。 有人可以幫我用正則表達式修改這段代碼嗎? 我對此進行了一些“研究”,但仍然不知道將其放在下面的代碼中的哪個位置。 謝謝。
Sub ReplaceStringInFile()
Dim objFSO As Object, objFil As Object, objFil2 As Object
Dim StrFileName As String, StrFolder As String, strAll As String, newFileText As String
Set objFSO = CreateObject("scripting.filesystemobject")
StrFolder = "c:\macro\"
StrFileName = Dir(StrFolder & "*.txt")
Do While StrFileName <> vbNullString
Set objFil = objFSO.opentextfile(StrFolder & StrFileName)
strAll = objFil.readall
objFil.Close
Set objFil2 = objFSO.createtextfile(StrFolder & StrFileName)
'change this to that in text
newFileText = Replace(strAll, "THIS", "THAT")
'change from to to in text
newFileText = Replace(newFileText, "from", "to")
'write file with new text
objFil2.Write newFileText
objFil2.Close
StrFileName = Dir
Loop
結束子
您可以使用此 function 刪除指定的模式
Public Function removePattern(searchPattern As String, strText As String) As String
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.Pattern = searchPattern
.IgnoreCase = True
.MultiLine = True
.Global = True
removePattern = .Replace(strText, vbNullString)
End With
End Function
然后將這行代碼添加到您的子程序中:
newFileText = removePattern("([\r\n" & Chr(11) & "]-)", strAll)
此模式查找各種換行符,然后是連字符。 Chr(11)
尋找軟返回 - 沒有等效的正則表達式占位符。 因此它必須作為字符串放在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.