如何在VBA中获得子匹配的位置?

时间:2016-09-14 12:26:41

标签: regex vba vbscript macros word-vba

我需要获取子匹配字符串的索引位置值。根据文档,我已阅读此Regular expression并了解FirstIndex属性以获取匹配字符串的位置。

但这只适用于一维匹配的字符串。我无法将FirstIndex应用于子匹配。 请参考sample matches

我试过这种格式,

        Dim myRegExp As Object, match As MatchCollection            
        Dim matched As String
        Set myRegExp = CreateObject("VBScript.RegExp")
        myRegExp.pattern = find
        If myRegExp.test(text) = True Then
        Set match = myRegExp.Execute(text)          
        Debug.Print match(0).submatches(0) '' this is matched string

我应该在哪里调用FirstIndex来获取子匹配字符串的位置

输出:

match(0)=>Berry, Brent. (2006). What accounts for race and ethnic differences in  Berry, 
Brent. parental financial transfers to adult children in the United States? Journal of Family
Issues 37:1583-1604.   

submatches(0)=>Berry, Brent.
submatches(6)=>2006

预期输出:

submatches(0) at 0th position
submatches(6) at 16th position and so on

2 个答案:

答案 0 :(得分:4)

您无法将.FirstIndex应用于SubMatches(x),因为它会返回String,而不是Match。如果组将返回唯一匹配,您只需使用Instr函数

即可找到其位置
With CreateObject("VBScript.RegExp")
    .Pattern = Find
    If .Test(text) Then
        Set match = .Execute(text)
        Debug.Print InStr(1, text, match(0).SubMatches(0)) '0
        Debug.Print InStr(1, text, match(0).SubMatches(5)) '16
        'and so on
    End If
End With

如果组返回唯一结果,您可以跟踪最后一个匹配的位置并循环结果。请注意,VBScript.RegExp并不支持后视广告,因此您不必考虑匹配的长度:

With CreateObject("VBScript.RegExp")
    .Pattern = find
    If .Test(text) Then
        Set match = .Execute(text)
        Dim i As Long, pos As Long, found As String
        pos = 1
        For i = 0 To match(0).SubMatches.Count - 1
            found = match(0).SubMatches(i)
            pos = InStr(pos, text, match(0).SubMatches(i)) 
            Debug.Print found, pos
        Next
    End If
End With

答案 1 :(得分:0)

Submatches collection包含字符串:

  

SubMatches集合包含单个子匹配字符串,......

     

SubMatches集合中的每个项目都是找到的字符串   由正则表达式捕获。

所以你无法获得职位/指数。