How do i use regex using instr in VBA
I am trying to use regex and kept on getting an error(compiler error) LIST SEPARATOR.Can anyone tell me which part im doing wrong.
if instr(1,regex.Pattern([A-Z]?dtest(rt,1)),b)>0 then
Solution 1:
InStr() has this format:
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)
It returns a number (Variant - Long) - the index where searchForText
is found within searchInText
Try using these options:
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