regex - 如何修改日期格式的正则表达式?
问题描述
我是从Reddit 上的/r/sysadmin那里得到的,但是日期格式不同,因为这个家伙来自欧洲,而且他使用了正则表达式,我对它还很陌生。
使用 RegEx 作为过滤器填充的数组将变为空,因为 RegEx 不正确,并且设置了 DateTime 格式的行出现错误,指出字符串无效。
我尝试将 DateTime 格式从dd.MM.yyyy
to更改为M.d.yyyy
然后匹配 RegEx,但这可能是错误的。
# Determine user's last logon time
# The script reads the output of "query.exe user" and parses the date
# and time returned by it using a regular expression.
# ADJUST: Make sure to change the regular expression to match your date format.
$query = query.exe user $env:username
($user, $logon, $matches) = ($null, $null, $null)
foreach ($line in $query)
{
$temp = $line -match '^\>([a-zA-Z0-9-_]+).*((\d{1}\.){1}\d{4}\ \d{2}\:\d{2})$'
}
$user = $matches[1]
$last_logon = $matches[2]
$getdt = (Get-Culture).DateTimeFormat
$DateFormat = $getdt.ShortDatePattern
$TimeFormat = $getdt.ShortTimePattern
$DateTimeFormat = '$DateFormat $TimeFormat'
# This calculates the timespan between NOW and the last time the user logged in
# ADJUST: Make sure the date format matches your locale
$last_logon_duration = (New-TimeSpan –Start ([datetime]::ParseExact($last_logon, `
'M.d.yyyy HH:mm', $null)) -End (Get-Date))
我希望它将用户名放入 中$user
,将 DateTime 放入 中$last_logon
,并将 DateTime 格式识别为有效。
At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:96 char:1
+ $user = $matches[1]
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Cannot index into a null array.
At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:97 char:1
+ $last_logon = $matches[2]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:104 char:1
+ $last_logon_duration = (New-TimeSpan –Start ([datetime]::ParseExact($ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
解决方案
要匹配M.dd.yyyy
,您应该将正则表达式更改为:
^\>([a-zA-Z0-9-_]+).*?(1?\d\.\d\d.\d\d\d\d \d\d\:\d\d)$
我明确地去掉了这些{...}
表达式,所以它让你更清楚它在做什么。
推荐阅读
- r - 如何根据 R 中的最小日期差异为每个 ID 仅选择一行数据?
- powerbi - 根据同一表的另一列获取特定列的计数 - Power BI
- openvino - 问:如何获取 dldt buildinfo?
- django - 在 React 前端显示 rtsp 流
- excel - 宏按钮将文件移动到另一个文件夹
- node.js - 如何在构建模板时修复离子错误
- javascript - 如何以数组中的对象为条件在 Json 表单中使用规则?
- google-cloud-platform - 从 Google Cloud 内部 IP 调用 Google Cloud 存储桶
- blender - Blender:没有对象附加纹理
- javascript - 仅替换单击元素的内部部分