[英]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.