VBA 使用正则表达式执行方法在一个字符串中进行多个匹配 [英] VBA multiple matches within one string using regular expressions execute method

查看:115
本文介绍了VBA 使用正则表达式执行方法在一个字符串中进行多个匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

尝试更改行 With Regex

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

你的 On Error resume next 语句掩盖了错误.

Your On Error resume next statement is disguising the error.

这篇关于VBA 使用正则表达式执行方法在一个字符串中进行多个匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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