简体   繁体   English

使用 MS-Word VBA 正则表达式搜索和替换文本文件内容

[英]Search and replace text file content using MS-Word VBA Regex

I'm currently using this code below (Thanks Maco for that) to replace multiple text file without opening and replace them manually.我目前正在使用下面的代码(感谢 Maco)来替换多个文本文件而不打开并手动替换它们。 It work pretty well, but I want it to be able to replace something like, for example, sometime the content contaning error, like:它工作得很好,但我希望它能够替换一些东西,例如,有时内容包含错误,比如:

exem例题

-tion

I just want to remove the enter mark at the end of the line and the dash so that the word "exemtion" is correct.我只想删除行尾的输入标记和破折号,以便“exemtion”这个词是正确的。 A simple macro in Notepad++ can do it easily but then you have to open each file manually to do it, not so efficient for hundred of file. Notepad ++中的一个简单宏可以轻松完成,但是您必须手动打开每个文件才能做到这一点,对于数百个文件来说效率不高。 Can somebody help me modified this code with Regex in it?有人可以帮我用正则表达式修改这段代码吗? I do some "research" about it but still don't know where to put it in the code below.我对此进行了一些“研究”,但仍然不知道将其放在下面的代码中的哪个位置。 Thanks.谢谢。

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

End Sub结束子

You can use this function to remove a specified pattern您可以使用此 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

Then add this line of code to your sub:然后将这行代码添加到您的子程序中:

newFileText = removePattern("([\r\n" & Chr(11) & "]-)", strAll)

This pattern looks for all kinds of line breaks followed by a hypen.此模式查找各种换行符,然后是连字符。 Chr(11) looks for the soft return - there is no equivalent regex-placeholder. Chr(11)寻找软返回 - 没有等效的正则表达式占位符。 Therefore it has to be put there as string.因此它必须作为字符串放在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM