如何在 VBA 中使用 instr 来使用正则表达式

如何在 VBA 中使用 instr 来使用正则表达式

我正在尝试使用正则表达式,但一直出现错误(编译器错误)LIST SEPARATOR。有人能告诉我我做错了哪部分吗?

 if instr(1,regex.Pattern([A-Z]?dtest(rt,1)),b)>0 then

答案1

InStr() 具有这种格式

InStr(startCharacter, searchInText, searchForText, compareMode)


startCharacter - a number (Long)
searchInText   - string (no RegEx, or pattern matching, or wildcard characters)
searchForText  - string (no RegEx, or pattern matching, or wildcard characters)
compareMode    - a number (from -1 to 2)

searchForText它返回一个数字 (Variant - Long) -在其中找到的索引searchInText


尝试使用这些选项:

Option Explicit

Sub findTxt()
    Debug.Print InStrRegEx("987xyz", "[A-Z]")                   ' -> 4
    Debug.Print getText("987xyz", "[A-Z]")                      ' -> x

    Debug.Print InStr(1, "987xyz", "x")                         ' -> 4
    Debug.Print InStr(1, "987xyz", getText("987xyz", "[A-Z]"))  ' -> 4

    Debug.Print "987xyz" Like "*[A-Za-z]"                       ' -> True
End Sub

Public Function InStrRegEx(ByVal searchIn As String, ByVal searchFor As String) As Long
    Dim regEx As Object, found As Object
    If Len(searchIn) > 0 And Len(searchFor) > 0 Then
        Set regEx = CreateObject("VBScript.RegExp")
        regEx.Pattern = searchFor
        regEx.Global = True
        regEx.IgnoreCase = True
        Set found = regEx.Execute(searchIn)
        If found.Count <> 0 Then InStrRegEx = found(0).FirstIndex + 1
    End If
End Function

Public Function getText(ByVal searchIn As String, ByVal searchFor As String) As String
    Dim regEx As Object, found As Object
    If Len(searchIn) > 0 And Len(searchFor) > 0 Then
        Set regEx = CreateObject("VBScript.RegExp")
        regEx.Pattern = searchFor
        regEx.Global = True
        regEx.IgnoreCase = True
        Set found = regEx.Execute(searchIn)
        If found.Count <> 0 Then getText = CStr(found(0))
    End If
End Function

相关内容