问题
I am new here and almost as new to RegEx. I am trying to use a RegEx expression to convert dates in a string in this format 05-18-16 or 5-18-16 or 05 18 16 or 5 18 16 to YYYY MM DD format.
Note the dates in the string can be YY or YYYY.
I have the "Find" expression working, but having trouble with the replacement. I found some code on this site that I thought would work, but the result is always "1900 1 31" and not 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
Thank you all for reading and for any guidance provided.
回答1:
Start by adding leading zeros first by using this pattern first
\b(?=\d\b)
and replace with 0
Demo
then apply this pattern on the results
^(\d+)\D*(\d+)\D*(\d\d)$
and replace with 20$3 $1 $2
Demo
来源:https://stackoverflow.com/questions/37305359/regex-mm-dd-yyyy-to-yyyy-mm-dd