下面的VB6替换文本的程序为何对某些文本文件不起作用?
以下是对c:\temp.txt进行正则替换的一段代码,对多数文本文件都能起作用,但也有时对某些文本文件会报“无效的过程调用或参数”错,再调试时会指向代码尾部的“objFile.WriteLine strTxt”并将c:\temp.txt中的文本全部删除使其变为0字节文件。
如果运行代码前将c:\temp.txt(可点击下面链接下载)在记事本中打开不做任何改动仅重新存盘一次,再运行代码又没有上述问题了。
不知何故,请指点解决办法。谢谢!
http://dl.dbank.com/c0z8ljjfbc
Private Sub Command1_Click()' Const ForReading = 1 Const ForWriting = 2 Dim strTxt As String '用于查找替换的文本 Dim expTxt As String '查找串(可用正则表达式) Dim repTxt As String '替换串 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("c:\temp.txt", ForReading) strTxt = objFile.ReadAll objFile.Close strTxt = StrReplace(strTxt, "\\l\(([^\)]+)\)", "$1") strTxt = StrReplace(strTxt, "\\d\\fo\d+\\li\(([^\)]*)\)", "[CD#3]$1") strTxt = StrReplace(strTxt, "\\d\\fo\d+\(([^\)]*)\)", "[KG2]$1") '…… Set objFile = objFSO.OpenTextFile("c:\temp.txt", ForWriting) objFile.WriteLine strTxt objFile.Close Set objFSO = Nothing Set objFile = Nothing MsgBox "OK"End SubFunction StrReplace(strTxt As String, expTxt As String, repTxt As String) As String '正则替换的函数 Dim RegEx As New VBScript_RegExp_55.RegExp '定义一个新的正则表达式对象 RegEx.Global = True '全程查找 RegEx.IgnoreCase = False ' 区分大小写 RegEx.Pattern = expTxt StrReplace = RegEx.Replace(strTxt, repTxt)End Function