正则表达式 – 正则表达式仅返回1个匹配项
发布时间:2020-12-14 05:58:44 所属栏目:百科 来源:网络整理
导读:我的VBA函数应该使用一个引用一系列单位的字符串(即“WAL1-5”),然后返回另一个字符串. 我想拿参数,并把它放在一个逗号分隔的字符串中, 所以“WAL1-5”应该变成“WAL1,WAL2,WAL3,WAL4,WAL5”. 它并不总是一个数字.例如,我可能需要分离“DEV11-18”或类似的东
我的VBA函数应该使用一个引用一系列单位的字符串(即“WAL1-5”),然后返回另一个字符串.
我想拿参数,并把它放在一个逗号分隔的字符串中, 它并不总是一个数字.例如,我可能需要分离“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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |