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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16084909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:41:45  来源:igfitidea点击:

VBA multiple matches within one string using regular expressions execute method

regexvbasubstringmultiple-matches

提问by user1902208

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:

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

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

回答by osknows

Try changing the line With Regex

尝试更改线路 With Regex

to

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

Your On Error resume nextstatement is disguising the error.

你的On Error resume next陈述掩盖了错误。