写了个全字匹配替换函数,大家提点意见
'增强替换函数(2002-09-02)
'完全兼容VB Replace()函数,支持全字匹配
'参数
'strExpress 源字符串
'strFind 要查找的字符串
'strReplace 替换字符串
'lngStart 开始位置 缺省为从头(1)开始
'lngCount 替换次数 缺省为-1替换所有
'blnMatchAll 是否全字匹配(缺省=True)
'strSplitChar (全字匹配)区分关键字符
'例:(1)strReturn = ReplaceEx("mydog,my", "my", "Mine", 1, -1, vbTextCompare)
'strReturn="mydog,Mine
'(2)ReplaceEx("a bbCC bb,cC", "bb", "qq")==>"a bbCC qq,cC"
Public Function ReplaceEx(ByVal strExpress As String, ByVal strFind As String _
, ByVal strReplace As String, Optional ByVal lngStart As Long = 1 _
, Optional ByVal lngCount As Long = -1 _
, Optional ByVal Compare As VbCompareMethod = vbTextCompare _
, Optional ByVal blnMatchAll As Boolean = True _
, Optional ByVal strSplitChar As String = ",.:;<>()/\+-=*| ") As String
Dim lngPos As Long
Dim intLen As Integer '要查找的字符串的长度
Dim lngRepCount As Long '已经替换的次数
Dim strSour As String '最后返回的值
Dim chLeft As String '左边那个字符
Dim chRight As String '右边那个字符
Dim strLeft As String
Dim strRight As String
Dim blnCanReplace As Boolean
strSour = strExpress
If strSour = "" Then GoTo ReplaceOver
If strFind = "" Then GoTo ReplaceOver
If lngCount = 0 Then GoTo ReplaceOver
If blnMatchAll Then
Debug.Assert strSplitChar <> ""
End If
intLen = Len(strFind)
lngRepCount = 0
lngPos = InStr(lngStart, strSour, strFind, Compare)
Do While (lngPos > 0)
'取出关键字‘strFind’左右的字符串
strLeft = Left(strSour, lngPos - 1)
strRight = Mid(strSour, lngPos + intLen)
blnCanReplace = True
If blnMatchAll Then '要求全字匹配
'左右字符是分隔字符,替换
If lngPos > 1 Then
chLeft = Mid(strSour, lngPos - 1, 1)
blnCanReplace = (InStr(1, strSplitChar, chLeft, vbTextCompare) > 0)
Else
blnCanReplace = True
End If
If blnCanReplace Then
chRight = Mid(strSour, lngPos + intLen, 1)
If chRight = "" Then 'lngPos 已经是最后位置
blnCanReplace = True
Else
blnCanReplace = (InStr(1, strSplitChar, chRight, vbTextCompare) > 0)
End If
End If
End If
If blnCanReplace Then
strSour = strLeft & strReplace & strRight '替换一次
lngRepCount = lngRepCount + 1
End If
'是否继续搜索
If lngRepCount < lngCount Or lngCount = -1 Then
lngStart = lngStart + intLen
lngPos = InStr(lngStart, strSour, strFind, Compare)
Else
Exit Do
End If
Loop
ReplaceOver:
ReplaceEx = strSour
End Function