MSREP在REPLACE函数中使用通配符

时间:2018-08-20 13:52:48

标签: vba ms-access replace wildcard

我正在尝试做一些简单的事情,但我不明白为什么它不起作用。我真的是MS Access VBA的新手。

我在文本框中有一个字符串:

\\ p9990cdc \ C $ \ Temp

我想将其转换为:
C:\ Temp

我正在尝试:

strSelectedFile = Replace(strSelectedFile, "\\*\C$", "C:")

它不起作用。

不确定RegEx为什么也不起作用:

strSelectedFile = Replace(strSelectedFile, "\\[\w]\C$", "C:")

所有设置都正确,因此问题出在那个替换代码上,因为如果我尝试例如:

strSelectedFile = Replace(strSelectedFile, "C$", "C:")

它有效并且成功地用C替换了C $:

\ p9990cdc \ C:\ Temp

我该如何进行这项工作?

非常感谢您的时间!

3 个答案:

答案 0 :(得分:2)

Replace不执行通配符。您可以实现自己的功能,也可以使用VBScript.RegEx使用正则表达式。

我写了一个小函数来帮你。但是性能并不理想,我只做了一些测试。它适用于您的示例输入。

Public Function LikeReplace(strInput As String, strPattern As String, strReplace As String, Optional start As Long = 1)
    Dim LenCompare As Long
    Do While start <= Len(strInput)
        For LenCompare = Len(strInput) - start + 1 To 1 Step -1
            If Mid(strInput, start, LenCompare) Like strPattern Then
                strInput = Left(strInput, start - 1) & strReplace & Right(strInput, Len(strInput) - (start + LenCompare - 1))
            End If
        Next
        start = start + 1
    Loop
    LikeReplace = strInput
End Function

使用您的输入并将Replace与此LikeReplace交换就可以了。

答案 1 :(得分:2)

您只能使用VBScript.RegEx和正确的模式。

Public Function ReplacePattern(ByRef iString As String, iSearchPattern As String, iReplaceWith As Variant)
'---------------------------------------------------------------------------------------
' Procedure : ReplacePattern
' Purpose   : Searches a string by pattern and replaces the text with given value
' Returns   : Replaced string.
'---------------------------------------------------------------------------------------
'

    Dim RE As Object
    Set RE = CreateObject("VBScript.RegExp")

    RE.ignorecase  = True 
    RE.Global      = True

    RE.Pattern     = iSearchPattern
    iString        = RE.Replace(iString, iReplaceWith)
    ReplacePattern = iString

    On Error Resume Next
    Set RE = Nothing

End Function

详细了解模式Here

模式:"^\\\\.*C\$" =>以\\开头,除了换行符+ C $以外的任意数量的字符

用法

?replacepattern("\\p9990cdc\C$\Temp","^\\\\.*C\$","C:") => C:\Temp

答案 2 :(得分:1)

您可以改用import sys, errno sys.exit(errno.EINTR) 查找Mid(Instr())的索引,然后从那里获取字符串(减1以保留目录字母)。

$