正则表达式将日期格式从dd-mon-yy转换为dd / MM / yy

时间:2016-02-27 15:16:47

标签: regex powershell

想知道,powershell中的正则表达式可以将日期从dd-mon-yy替换为dd / MM / yy

示例:25-FEB-16更改为25/02/16

2 个答案:

答案 0 :(得分:1)

这里更好的解决方案是使用日期解析和格式化函数,而不是基于正则表达式的字符串替换。

[DateTime]::ParseExact('25-FEB-16', 'dd-MMM-yy', $null).ToString('dd/MM/yy', [System.Globalization.CultureInfo]::InvariantCulture)
# => 25/02/16

如果您在日期与其他语言的月份名称一起运行的系统上运行,这也可以获得内置的区域设置灵敏度。但是使用ParseExactInvariantCulture选项意味着区域设置敏感度不会影响您指定的格式。

答案 1 :(得分:1)

您应该使用[DateTime]::ParseExact(),因为正则表达式需要12个不同的替换操作,或者MatchEvalutor来转换月份。

使用正则表达式MatchEvaluator的示例:

$MatchEvaluator = {  
  param($match) 

  #Could have used a switch-statement too..
  $month = [datetime]::ParseExact($match.Groups[2].Value,"MMM",$null).Month

  "{0:00}/{1:00}/{2:00}" -f $match.Groups[1].Value, $month, $match.Groups[3].Value
}

[regex]::Replace("25-FEB-16","(\d+)-(\w+)-(\d+)", $MatchEvaluator)
25/02/16

考虑到这一点,我会说仅使用ParseExact()是一个更好的解决方案:

try {
    [datetime]::ParseExact("25-FEB-16","dd-MMM-yy", $null).ToString("dd/MM/yy", [cultureinfo]::InvariantCulture)
} catch {
    #Invalid date-format
}
25/02/16
相关问题