想知道,powershell中的regex是否可以替换从dd-mon-yy到dd/MM/yy的日期?
例子:25-2月16日改为25/02/16
发布于 2016-02-27 16:25:04
您应该使用[DateTime]::ParseExact(),因为regex需要12个不同的替换操作,或者一个MatchEvalutor来转换这个月。
使用regex 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发布于 2016-02-27 16:22:44
更好的解决方案是使用日期解析和格式化函数,而不是基于正则表达式的字符串替换。
[DateTime]::ParseExact('25-FEB-16', 'dd-MMM-yy', $null).ToString('dd/MM/yy', [System.Globalization.CultureInfo]::InvariantCulture)
# => 25/02/16这也会使您对内部环境敏感,以防您在另一种语言中的日期与月份名称一起运行的系统上运行。但是使用ParseExact和InvariantCulture选项意味着区域设置敏感性不会影响到指定的格式。
https://stackoverflow.com/questions/35671450
复制相似问题