lyk*_*lyk 5 regex excel vba string-split
我是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
Run Code Online (Sandbox Code Playgroud)
这就是我目前正在做的事情.但是,在RegEx.Split函数中似乎出现了问题,因为它似乎导致我的代码挂起而不能进一步处理.
为了确认,我做了一些简单的事情:
MsgBox("Hi")
pattern = "(/)|(,)|(-)"
dateStringArray() = RegEx.Split(dateString, pattern)
MsgBox("Bye")
Run Code Online (Sandbox Code Playgroud)
"嗨"msgbox弹出,但"再见"msgbox永远不会弹出,而且代码进一步下降似乎根本没有被剔除,这导致我怀疑RegEx.Split导致它被卡住了.
我可以检查一下我是否真的以正确的方式使用RegEx.Split?根据MSDN 这里,斯普利特(字符串,字符串)返回一个字符串数组为好.
谢谢!
编辑:我正在尝试不探索CDate()函数,因为我试图不依赖于用户计算机的区域设置.
Flo*_* B. 10
要在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
Run Code Online (Sandbox Code Playgroud)
用法示例:
Dim v
v = SplitRe("a,b/c;d", "[,;/]")
Run Code Online (Sandbox Code Playgroud)
Oli*_*ver -1
引用 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
Run Code Online (Sandbox Code Playgroud)
要进行测试,请致电:
MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!"))
Run Code Online (Sandbox Code Playgroud)
简而言之,您需要您的模式来匹配您想要提取的各个部分,中间有矛,也许是这样的:
"(\d+)[/-,](\d+)[/-,](\d+)"
Run Code Online (Sandbox Code Playgroud)
整个内容将在 oMatch 中,而数字 (\d) 将最终在 oMatch.SubMatches(0) 到 oMatch.SubMatches(2) 中。