Regex 根据时间的位置更换或修剪字符串
在Powershell中,我一直在使用正则表达式,并尝试根据时间的位置修剪字符串。目前,一个人手动输入字符串,因此它可以以多种方式出现。数据的格式如下Regex 根据时间的位置更换或修剪字符串,regex,powershell,Regex,Powershell,在Powershell中,我一直在使用正则表达式,并尝试根据时间的位置修剪字符串。目前,一个人手动输入字符串,因此它可以以多种方式出现。数据的格式如下 $appointment = "Certified Substitute Orientation (Session 1) - 9:00 AM - 11:00 AM" $appointment = "TBI 101 1:00 pm - 3:00 pm" 每一次,标题都会改变,时间也会有所不同。可能是:上午9点、上午9点、上午9点等等,我想试着找到
$appointment = "Certified Substitute Orientation (Session 1) - 9:00 AM - 11:00 AM"
$appointment = "TBI 101 1:00 pm - 3:00 pm"
每一次,标题都会改变,时间也会有所不同。可能是:上午9点、上午9点、上午9点等等,我想试着找到一种方法来打发时间,因为时间不会总是在同一个地方
我是这方面的新手。任何帮助都将不胜感激
多谢各位
我知道这是一个很大的问题,但我尝试过弄乱代码,看起来像这样,似乎无法让它工作:
If ($appointment -like "*Session 1*") {
$appointment1 = $appointment
$appointment = $appointment -creplace '[^1-9]*'
$appointment=$appointment.substring(0,$appointment.subject.length-1)
$appointment1 = $appointment1 -replace '-' -replace "[(]","" -replace "[)]","" -replace "event","" -replace "'" -replace '[,]',' ' -replace " "," " -replace " "," " -replace '[\d+]:.*'
}
我的目标是在时间之前拆分字符串,以便:
$appointment1 = "Certified Substitute Orientation (Session 1)"
$appointment2 = "9:00 AM - 11:00 AM"
使用更复杂的正则表达式,您甚至可以分离会话:
## Q:\Test\2019\08\22\SO_57614115.ps1
$appointments = @"
Certified Substitute Orientation (Session 1) - 9:00 AM - 11:00 AM
TBI 101 1:00 pm - 3:00 pm
"@ -split '\r?\n'
$RE = '^(?<title>.*?)[-_ ]*(?<session>\([^\)]*\))?[-_ ]*(?<from>1?\d:[0-5]\d\s*[ap]m)[-_ ]+(?<to>1?\d:[0-5]\d\s*[ap]m)$'
Foreach($appointment in $appointments){
if ($appointment -match $RE){
[PSCustomObject]@{
Title = $Matches.title
Session = $Matches.session
From = $Matches.from.ToUpper()
To = $Matches.to.ToUpper()
}
} else {
"doesn't match RE: $appointment"
}
}
用户将提出更多的变化,然后你可能希望得到正确的。你真的应该在输入端解决这个问题。$str-split'?=\d{1,2}:\d{1,2}[AP]M'难以抗拒:[regex]::匹配$appointment,'\d+:\d+。?:[AP]M',[System.Text.RegularExpressions.RegexOptions]::IgnoreCase{$.Value}@TheIncorrigible1-我认为这是我缺乏知识,但如果你也对此感到困惑,也许它有一个好的新问题的标志;解释:匹配操作符wll返回找到的第一个匹配项。
> Q:\Test\2019\08\22\SO_57614115.ps1
Title Session From To
----- ------- ---- --
Certified Substitute Orientation (Session 1) 9:00 AM 11:00 AM
TBI 101 1:00 PM 3:00 PM