微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 正则表达式仅返回1个匹配项

我的VBA函数应该使用一个引用一系列单位的字符串(即“WAL1-5”),然后返回另一个字符串.

我想拿参数,并把它放在一个逗号分隔的字符串中,
所以“WAL1-5”应该变成“WAL1,WAL2,WAL3,WAL4,WAL5”.

它并不总是一个数字.例如,我可能需要分离“DEV11-18”或类似的东西.

我从来没有使用正则表达式,但继续尝试不同的东西来使这项工作,它似乎只找到1匹配而不是3.

有任何想法吗?这是我的代码

Private Function split_metergroup(ByVal group As String) As String   
    Dim re As Object
    Dim matches As Object
    Dim result As String
    Dim prefix As String
    Dim startvar As Integer
    Dim endVar As Integer
    Dim i As Integer

    Set re = CreateObject("vbscript.regexp")
    re.Pattern = "([A-Z]+)(\d+)[-](\d+)"
    re.IgnoreCase = False
    Set matches = re.Execute(group)

    Debug.Print matches.Count

    If matches.Count <> 0 Then
        prefix = matches.Item(0)
        startvar = CInt(matches.Item(1)) 'error occurs here
        endVar = CInt(matches.Item(2))
        result = ""

        For i = startvar To endVar - 1
            result = result & prefix & i & ","
        Next i

        split_metergroup = result & prefix & endVar
    Else
        MsgBox "There is an error with splitting a meter group."
        split_metergroup = "ERROR"
    End If

End Function

我尝试设置global = true但我意识到这不是问题.错误实际上发生在评论的行上,但我认为这是因为只有一个匹配.

我试着谷歌搜索它,但每个人的情况似乎与我的有点不同,因为这是我第一次使用RE我不认为我理解模式足以看出是否可能是问题.

谢谢!

解决方法

尝试下面的修改功能

Private Function split_metergroup(ByVal group As String) As String

    Dim re As Object
    Dim matches As Variant
    Dim result As String
    Dim prefix As String
    Dim startvar As Integer
    Dim endVar As Integer
    Dim i As Integer

    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .IgnoreCase = True
        .Pattern = "[0-9]{1,20}" '<-- Modified the Pattern
    End With

    Set matches = re.Execute(group)                  
    If matches.Count > 0 Then
        startvar = CInt(matches.Item(0)) ' <-- modified 
        endVar = CInt(matches.Item(1)) ' <-- modified
        prefix = Left(group,InStr(group,startvar) - 1) ' <-- modified
        result = ""

        For i = startvar To endVar - 1
            result = result & prefix & i & ","
        Next i    
        split_metergroup = result & prefix & endVar
    Else
        MsgBox "There is an error with splitting a meter group."
        split_metergroup = "ERROR"
    End If

End Function

Sub我用它测试了它:

Option Explicit

Sub TestRegEx()

Dim Res As String

Res = split_metergroup("DEV11-18")
Debug.Print Res

End Sub

结果我进入了即时窗口:

DEV11,DEV12,DEV13,DEV14,DEV15,DEV16,DEV17,DEV18

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐