使用vbscript正则表达式来条件替换日期

时间:2016-06-11 12:22:44

标签: regex vbscript

我想使用正则表达式将字符串中的实际日期替换为YYYYMMDD。但是,我的字符串可能包含两种类型的日期,可能是20160531或160531.对于这两种,我必须用YYYYMMDD和YYMMDD替换它们。以下是两个例子:

Employment_salary_20160531 - > Employment_salary_YYYYMMDD

Employment_salary_160531 - > Employment_salary_YYMMDD

想知道是否可以在单个正则表达式中执行此操作而不使用IFELSE语句?

谢谢!

2 个答案:

答案 0 :(得分:0)

我不确定我是否正确。但似乎有两种不同的替换YYYYMMDDYYMMDD,只需一种模式就不可能做到这一点。

您可以通过以下方式匹配这两个分开的模式:

/(^(\d{4})(\d{2})(\d{2})$)|(^(\d{2})(\d{2})(\d{2})$)/

Online Demo

如您所见,上面的模式与20160531160531都匹配。但是,您无法使用YYYYMMDD (适用于20160531YYMMDD(适用于160531)替换它们。实际上,您可以使用YYYYMMDDYYMMDD替换它们。

如果你想要两个独立的替换,你需要两个独立的模式:

/^(\d{4})(\d{2})(\d{2})$/
/* and replace with `YYYYMMDD` */

/^(\d{2})(\d{2})(\d{2})$/
/* and replace with YYMMDD */

答案 1 :(得分:0)

这将为您提供准确的输入日期验证。另一个正则表达式会起作用,但它很脏。它将接受5000年。

简答:((19 | 20)\ d {2} | [0-9] {2})(0 [1-9] | 1 [0-2])([012] [0- 9] | 3 [0-1])

长期但经过彻底测试的答案......

stringtest1 = "Employment_salary_20160531"
stringtest2 = "Employment_salary_990212"
stringtest3 = "Employment_salary_990242"
wscript.echo : wscript.echo "---------------------------------------------------" : wscript.echo 
wscript.echo "Trying: " & stringtest1 & vbcrlf & vbcrlf & vbtab & " => " & sanitizedate(stringtest1)
wscript.echo : wscript.echo "---------------------------------------------------" : wscript.echo 
wscript.echo "Trying: " & stringtest2 & vbcrlf & vbcrlf & vbtab & " => " & sanitizedate(stringtest2)
wscript.echo : wscript.echo "---------------------------------------------------" : wscript.echo 
wscript.echo "Trying: " & stringtest3 & vbcrlf & vbcrlf & vbtab & " => " & sanitizedate(stringtest3)
wscript.echo : wscript.echo "---------------------------------------------------" : wscript.echo 

Function sanitizedate(str)
    Set objRE = New RegExp
    objRE.Pattern    = "((19|20)\d{2}|[0-9]{2})(0[1-9]|1[0-2])([012][0-9]|3[0-1])"
    objRE.IgnoreCase = True
    objRE.Global     = False
    objRE.Multiline  = true
    Set objMatch = objRE.Execute(str)
    If objMatch.Count = 1 Then
        Select Case Len(objMatch.Item(0))
            Case "8"
                sanitizedate = Replace(str, objMatch.Item(0), "YYYYMMDD")
            Case "6"
                sanitizedate = Replace(str, objMatch.Item(0), "YYMMDD")
        End Select
    Else
        sanitizedate = str
    End if
End Function

验证结果

尝试:Employment_salary_20160531

     => Employment_salary_YYYYMMDD

尝试:Employment_salary_990212

     => Employment_salary_YYMMDD

尝试:Employment_salary_990242 失败,因为42不是有效日期

     => Employment_salary_990242