我是VBA的新手,想在使用RegEx方面寻求一些帮助,我希望能以某种方式启发我的错误。我目前正在尝试将日期分为单独的日期,月份和年份,可能的分隔符包括“,”,“ - ”和“/”。
Function formattedDate(inputDate As String) As String
Dim dateString As String
Dim dateStringArray() As String
Dim day As Integer
Dim month As String
Dim year As Integer
Dim assembledDate As String
Dim monthNum As Integer
Dim tempArray() As String
Dim pattern As String()
Dim RegEx As Object
dateString = inputDate
Set RegEx = CreateObject("VBScript.RegExp")
pattern = "(/)|(,)|(-)"
dateStringArray() = RegEx.Split(dateString, pattern)
' .... code continues
这就是我目前正在做的事情。但是,在RegEx.Split函数中似乎出现了问题,因为它似乎导致我的代码挂起而不能进一步处理。
为了确认,我做了一些简单的事情:
MsgBox("Hi")
pattern = "(/)|(,)|(-)"
dateStringArray() = RegEx.Split(dateString, pattern)
MsgBox("Bye")
“嗨”msgbox弹出,但“再见”msgbox永远不会弹出,而且代码进一步下降似乎根本没有被取消,这导致我怀疑RegEx.Split导致它卡住了。
我可以检查一下我是否真的以正确的方式使用RegEx.Split?根据MSDN here,Split(String,String)也返回一个字符串数组。
谢谢!
编辑:我正在尝试不探索CDate()函数,因为我试图不依赖于用户计算机的区域设置。
答案 0 :(得分:8)
在VBA中使用正则表达式拆分字符串:
Public Function SplitRe(Text As String, Pattern As String, Optional IgnoreCase As Boolean) As String()
Static re As Object
If re Is Nothing Then
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.MultiLine = True
End If
re.IgnoreCase = IgnoreCase
re.Pattern = Pattern
SplitRe = Strings.Split(re.Replace(text, ChrW(-1)), ChrW(-1))
End Function
用法示例:
Dim v
v = SplitRe("a,b/c;d", "[,;/]")
答案 1 :(得分:0)
引用VbScript Regexp文档中的示例: https://msdn.microsoft.com/en-us/library/y27d2s18%28v=vs.84%29.aspx
Function SubMatchTest(inpStr)
Dim retStr
Dim oRe, oMatch, oMatches
Set oRe = New RegExp
' Look for an e-mail address (not a perfect RegExp)
oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
' Get the Matches collection
Set oMatches = oRe.Execute(inpStr)
' Get the first item in the Matches collection
Set oMatch = oMatches(0)
' Create the results string.
' The Match object is the entire match - dragon@xyzzy.com
retStr = "Email address is: " & oMatch & vbNewLine
' Get the sub-matched parts of the address.
retStr = retStr & "Email alias is: " & oMatch.SubMatches(0) ' dragon
retStr = retStr & vbNewLine
retStr = retStr & "Organization is: " & oMatch.SubMatches(1) ' xyzzy
SubMatchTest = retStr
End Function
要测试,请致电:
MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!"))
简而言之,你需要你的模式来匹配你想要提取的各个部分,其间的是spearators,可能是这样的:
"(\d+)[/-,](\d+)[/-,](\d+)"
整个事情将在oMatch中,而数字(\ d)将以oMatch.SubMatches(0)结束到oMatch.SubMatches(2)。