Excel VBA正则expression式匹配位置

如何在正则expression式中获取第一个匹配结果的位置? 见下文。

Function MYMATCH(strValue As String, strPattern As String, Optional blnCase As Boolean = True, Optional blnBoolean = True) As String Dim objRegEx As Object Dim strPosition As Integer ' Create regular expression. Set objRegEx = CreateObject("VBScript.RegExp") objRegEx.Pattern = strPattern objRegEx.IgnoreCase = blnCase ' Do the search match. strPosition = objRegEx.Match(strValue) MYMATCH = strPosition End Function 

首先,我不完全确定.Match返回的是什么(string,整数等)。 我发现的一个解决scheme说,我应该创build一个Match对象,然后从那里抓住位置,但不像vb , vba不能识别Match对象。 我也看到了一些像下面这样的代码 ,但是我不一定是在寻找值,只是第一个string的位置:

 If allMatches.count <> 0 Then result = allMatches.Item(0).submatches.Item(0) End If 

有些人忽略了上面可能出现的任何语法错误(主要是因为我左右改变了variablestypes),我该如何轻松/简单地完成这个任务?

谢谢!

您可以使用FirstIndex来使用Execute方法返回匹配的位置,即

 Function MYMATCH(strValue As String, strPattern As String, Optional blnCase As Boolean = True, Optional blnBoolean = True) As String Dim objRegEx As Object Dim strPosition As Integer Dim RegMC ' Create regular expression. Set objRegEx = CreateObject("VBScript.RegExp") With objRegEx .Pattern = strPattern .IgnoreCase = blnCase If .test(strValue) Then Set RegMC = .Execute(strValue) MYMATCH = RegMC(0).firstindex + 1 Else MYMATCH = "no match" End If End With End Function Sub TestMe() MsgBox MYMATCH("test 1", "\d+") End Sub 

为了可能有这个问题的其他人的利益,我终于弄清楚了。

 Option Explicit Function CHAMATCH(strValue As String, strPattern As String, Optional blnCase As Boolean = True, Optional blnBoolean = True) As String Dim objRegEx As Object Dim objPosition As Object Dim strPosition As String ' Create regular expression. Set objRegEx = CreateObject("VBScript.RegExp") objRegEx.Pattern = strPattern objRegEx.IgnoreCase = blnCase ' Do the search match. Set objPosition = objRegEx.Execute(strValue) strPosition = objPosition(0).FirstIndex CHAMATCH = strPosition End Function 

而不是一个Matchtypes,只是一个常规的Objecttypes会做(考虑到它所返回的是一个类)。 然后,如果要抓取索引位置,只需在[您select的]匹配上使用.FirstIndex ,或者如果您想要值,则使用.Value