RegEx MM DD YYYY至YYYY MM DD

时间:2016-05-18 16:32:15

标签: regex date

我是新来的,几乎和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

感谢大家阅读和提供任何指导。

1 个答案:

答案 0 :(得分:1)

首先使用此模式首先添加前导零

\b(?=\d\b)

并替换为0
Demo

然后在结果上应用此模式

^(\d+)\D*(\d+)\D*(\d\d)$

并替换为20$3 $1 $2
Demo