VBA使用正则表达式执行方法在一个字符串中进行多次匹配

时间:2013-04-18 13:53:59

标签: regex vba substring multiple-matches

我正在尝试根据1.度数来匹配各种职位的经验水平.2。经验年数。模式相当简单(例如:“BS / 5”将是具有5年经验的科学学士学位。我也有符合此方案的条目,但在同一个字符串中具有多个学位和经验水平(例如:“BS / 5-MS / 2“)被认为是等价的。我有一个基本的函数,它将匹配并找到子字符串模式,但它永远不会返回多个匹配,即使我已将.Global属性设置为true for regexp对象。任何想法?代码如下:

On Error Resume Next
ActiveWorkbook.VBProject.References.AddFromGuid "{3F4DACA7-160D-11D2-A8E9-00104B365C9F}", 5, 5

Dim theRegex As Object
Dim theString As String 

Set theRegex = CreateObject("VBScript.RegExp")

With regex
    .MultiLine = False
    .Global = True
    .IgnoreCase = False
End With

theRegex.Pattern = "([A-z][A-z][A-z]?/[0-9][0-9]?)"

theString = "MS/9-PhD/4"

Set MyMatches = theRegex.Execute(theString)

Debug.Print "SubMatches.Count: " & MyMatches.Item(0).SubMatches.Count

If MyMatches.Count <> 0 Then
        With MyMatches
            For myMatchCt = 0 To .Count - 1
                    Debug.Print "myMatchCt: " & myMatchCt
                    For subMtCt = 0 To .Item(subMtCt).SubMatches.Count - 1
                        Debug.Print "subMtCt: " & subMtCt
                        Debug.Print ("," & .Item(myMatchCt).SubMatches.Item(subMtCt))
                    Next
            Next
        End With
    Else
    Debug.Print "No Matches"
End If

1 个答案:

答案 0 :(得分:3)

尝试更改第With Regex

With theRegex
    .MultiLine = False
    .Global = True
    .IgnoreCase = False
End With

您的On Error resume next声明掩盖了错误。