如何获得VBA中子比赛的位置? [英] How to get the position of submatches in VBA?

查看:76
本文介绍了如何获得VBA中子比赛的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取匹配的字符串的索引位置值.根据文档,我已经阅读了

I need to get the index position value of submatched string. As per documentation, I have read through this Regular expression and got to know FirstIndex property to get the position of matched string.

但这仅适用于一维匹配的字符串.我无法将FirstIndex应用于子比赛. 请参考示例匹配项

But this works only for one dimensional matched string. I couldn't apply FirstIndex for submatches. Pls refer 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以获得匹配的字符串的位置

Where should I call FirstIndex to get position of submatched string

输出:

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

推荐答案

您不能将.FirstIndex应用于SubMatches(x),因为它会返回String,而不是Match.如果这些组将返回唯一的匹配项,则只需使用Instr函数即可找到其位置:

You can't apply .FirstIndex to SubMatches(x) because it returns a String, not a Match. If the groups will return unique matches, you can find its location by simply using the Instr function:

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不支持回溯,因此您不必考虑匹配的长度:

If the groups will not return unique results, you can track the position of the last match and loop through the results. Note that VBScript.RegExp doesn't support look-behinds, so you don't have to take the length of the matches into account:

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

这篇关于如何获得VBA中子比赛的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆