我的 VBA 函数应该采用引用一系列单位的字符串(即 "WWW1-5"
),然后返回另一个字符串。
我想获取参数,并将其放入逗号分隔的字符串中,
所以“WWW1-5”
应该变成“WWW1,WWW2,WWW3,WWW4,WWW5”。
它并不总是一个数字。例如,我可能需要分隔 "XXX11-18"
或类似的内容。
我从未使用过正则表达式,但不断尝试不同的方法来完成这项工作,但似乎只找到 1 个匹配项,而不是 3 个。
有什么想法吗?这是我的代码:
Private Function split_group(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_group = result & prefix & endVar
Else
MsgBox "There is an error with splitting a group."
split_group = "ERROR"
End If
End Function
我尝试设置 global = true 但我意识到这不是问题。该错误实际上发生在带有注释的行上,但我认为这是因为只有 1 个匹配项。
我尝试用谷歌搜索它,但每个人的情况似乎都与我的有点不同,因为这是我第一次使用 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
关于regex - 正则表达式仅返回 1 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457449/