我有一个域description
,其中包含可预测格式的文本,看起来像这两个选项中的一个,
DEACTIVATED on Tue Apr 02 2019
或
DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith
在每种情况下,我只需要获取日期Tue Apr 02 2019
,同时考虑到该日期之后是否有文字。
用例示例
$string = "DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith"
$date = "Tue Apr 02 2019"
答案 0 :(得分:0)
不确定我是否理解正确,但是子字符串的工作方式如下:
$string = "DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith"
#.substring(starting point, how many)
$date = $string.Substring(15,10)
$date
Tue Apr 02
答案 1 :(得分:0)
这是我得到的方式,因为我不得不考虑对象之间的某些潜在差异
$text = "DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith"
$start_pos = $text.IndexOf('on')
$substring = $text.substring($start_pos + 3)
if ($text.IndexOf(' | ') -gt -1) {
$end_pos = $text.indexOf(' | ')
$substring = $substring.substring(0, $end_pos)
}
答案 2 :(得分:0)
这是完成工作的略有不同的方法。 [咧嘴]
它做什么...
DEACTIVATED on
之后的日期字符串[datetime]
对象并显示这是代码...
$DescriptionText = @(
'DEACTIVATED on Sat May 11 2019'
'DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith'
)
foreach ($DT_Item in $DescriptionText)
{
$Null = $DT_Item.Split('|')[0].Trim() -match 'DEACTIVATED on (?<DeactivationDate>.+)'
$Matches.DeactivationDate
[datetime]::ParseExact($Matches.DeactivationDate, 'ddd MMM dd yyyy', $Null)
'=' * 20
}
输出...
Sat May 11 2019
2019 May 11, Saturday 12:00:00 AM
====================
Tue Apr 02 2019
2019 April 02, Tuesday 12:00:00 AM
====================
我不知道第一对输出中的空白行是从哪里来的。 [脸红]
答案 3 :(得分:0)
我会使用:
::ParseExact()
广播/转换为[datetime]类型## Q:\Test\2019\05\09\SO_56060672.ps1
$strings = @"
DEACTIVATED on Tue Apr 02 2019
DEACTIVATED on Tue Apr 09 2019 | MANAGER John Smith
"@ -split '\r?\n'
$RE = '(?<=DEACTIVATED on ).*\d{4}'
## Output found datetime strings
$strings | Select-String $RE | ForEach-Object{$_.Matches.value}
## if your locale is English convert to [datetime] type
$strings | Select-String $RE | ForEach-Object{
[datetime]::ParseExact($_.Matches.value,'ddd MMM dd yyyy',$null)
}
## if your locale is NOT English convert to [datetime] type
$strings | Select-String $RE | ForEach-Object{
[datetime]::ParseExact($_.Matches.value,'ddd MMM dd yyyy',
[System.Globalization.CultureInfo]::InvariantCulture)
}
在我的德语语言环境中,第一个和最后一个输出:
Tue Apr 02 2019
Tue Apr 09 2019
Dienstag, 2. April 2019 00:00:00
Dienstag, 9. April 2019 00:00:00