正则表达式 MM DD YYYY 到 YYYY MM DD
Posted
技术标签:
【中文标题】正则表达式 MM DD YYYY 到 YYYY MM DD【英文标题】:RegEx MM DD YYYY to YYYY MM DD 【发布时间】: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])( |-)((?:\d4|\d2))", "$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])( |-)((?:\d4|\d2))", 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 时间您可以在单元格上设置格式 【参考方案1】:首先使用此模式首先添加前导零
\b(?=\d\b)
并替换为0
Demo
然后将此模式应用于结果
^(\d+)\D*(\d+)\D*(\d\d)$
并替换为20$3 $1 $2
Demo
【讨论】:
阿尔法布拉沃,感谢您的回复。我为 05 09 16 之类的东西工作,但不适用于我提供的示例。 Sub StackExPost() Dim strIn As String, strReturn As String strIn = "05 09 16" 'strIn = "Test 05 09 16 and 5-9-2016 Test" '不起作用 strReturn = fcnRegEx(strIn, "\b( ?=\d\b)", "0") strReturn = fcnRegEx(strIn, "^(\d+)\D*(\d+)\D*(\d\d)$", "20$3 $1 $2" ) MsgBox strReturn End Sub 将第二个模式应用于第一个模式的结果时,将strReturn = fcnRegEx(strIn, "^(\d+)\D*(\d+)\D*(\d\d)$", "20$3 $1 $2")
更改为strReturn = fcnRegEx(strReturn, "^(\d+)\D*(\d+)\D*(\d\d)$", "20$3 $1 $2")
。以上是关于正则表达式 MM DD YYYY 到 YYYY MM DD的主要内容,如果未能解决你的问题,请参考以下文章
用于验证日期时间格式的正则表达式(MM/DD/YYYY)[重复]