Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

regex - VBA multiple matches within one string using regular expressions execute method

I'm trying to match experience levels for various positions based on 1. Degree 2. Years of Experience. The pattern is fairly simple (example: "BS/5" would be a bachelors of science with 5 years of experience. I also have entries that follow this scheme but have multiple degrees and experience levels in the same string (example: "BS/5-MS/2") that are considered equivalent. I've got a basic function that will match and find the substring pattern but it never returns more than one match even though I've set the .Global property to true for the regexp object. Any ideas? Code below:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try changing the line With Regex

to

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

Your On Error resume next statement is disguising the error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...