【发布时间】:2016-05-18 16:32:15
【问题描述】:
我是新来的,几乎和 RegEx 一样新。我正在尝试使用 RegEx 表达式将格式为 05-18-16 或 5-18-16 或 05 18 16 或 5 18 16 的字符串中的日期转换为 YYYY MM DD 格式。
注意字符串中的日期可以是 YY 或 YYYY。
我可以使用“查找”表达式,但在替换时遇到了问题。我在这个网站上找到了一些我认为可以工作的代码,但结果总是“1900 1 31”而不是 2016 05 18”
Sub StackExPost()
Dim strIn As String, strReturn As String
strIn = "Test 05 09 16 and 5-9-2016 Test"
strReturn = fcnRegEx(strIn, "\b(0?[1-9]|1[0-12])( |-)(0?[1-9]|[1-2][0-9]|3[0-1])( |-)((?:\d{4}|\d{2}))", "$5 $3 $1")
MsgBox strReturn 'I get get and transpose the components.
strReturn = fcnRegEx(strIn, "\b(0?[1-9]|1[0-12])( |-)(0?[1-9]|[1-2][0-9]|3[0-1])( |-)((?:\d{4}|\d{2}))", Format("$5", "YYYY") & " " & Format("$2", "MM") & " " & Format("$1", "DD"))
MsgBox strReturn '... but can't apply the formatting.
End Sub
Function fcnRegEx(strIn As String, strPattern As String, Optional strReplace As String = vbNullString, Optional bGlobal As Boolean = True)
Dim objRegex As Object
Dim objRegM As Object
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Global = bGlobal
With objRegex
.IgnoreCase = True
.Pattern = strPattern
If .Test(strIn) Then
Set objRegM = .Execute(strIn)
If strReplace = vbNullString Then
fcnRegEx = objRegM(0).Value 'submatches(0)
Else
fcnRegEx = objRegex.Replace(strIn, strReplace)
End If
Else
fcnRegEx = "//No Match\\"
End If
End With
lbl_Exit:
Exit Function
End Function
感谢大家的阅读和提供的任何指导。
【问题讨论】:
-
为什么不使用unix时间?这似乎是 excel 和/或 vba,因此使用 unix 时间您可以在单元格上设置格式