我是同时使用powershell和regex的新手,但认为这是验证文件夹中文件名格式的解决方案。文件名通常应看起来像...
“ 01234-Corres-我的研究的示例标题-2015-12-03.msg”
并使用此脚本进行匹配...
$MyStudyPath = "C:\Users\higginsr4\Test\StudyExamples\SmallMsgFolder"
$MyStudyNumber = "06327"
#Get-ChildItem -path $MyStudyPath -filter *.msg | where-object {$_.Name -match $($MyStudyNumber+' - corres - *' + '\d\d\d\d-\d\d-\d\d.msg')}
Get-ChildItem -path $MyStudyPath -filter *.msg | where-object {$_.Name -match $($MyStudyNumber+' - corres - *')}
此代码行...
Get-ChildItem -path $MyStudyPath -filter *.msg | where-object {$_.Name -match $($MyStudyNumber+' - corres - *')}
工作正常,但我希望能够使用正则表达式通配符来匹配任何“我的研究的示例标题”,然后使用正则表达式将日期与上面脚本中注释行中的语法匹配。问题是此注释行与任何内容都不匹配,并且正使用正则表达式来匹配日期,从而难以解决问题。
任何帮助表示赞赏...
答案 0 :(得分:2)
尝试使用此模式01234 - [cC]orres - [\w -]+? \d{4}-\d{2}-\d{2}
。
很显然,01234
可以替换为您输入的数字并连接模式。
然后,它与corres
或Corres
匹配,后跟一系列非贪婪([\w -]+?
)单词字符,空格或连字符,因此它也不会消耗日期。然后它匹配日期:\d{4}-\d{2}-\d{2}
,但是您必须确定格式。要包括其他格式,您可以使用以下格式:(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2}\/\d{4})
答案 1 :(得分:1)
我建议使用另一个选项来验证文件名。您怎么知道所有名字都是正确的? Where子句忽略不正确的匹配。试试这个:
#sample data
"" | Out-file '01234 - Corres - Example title of my study - 2015-12-03.msg'
"" | Out-file '01234 - Word - My study - 2017-11-05.msg'
"" | Out-file '12345 - Other Word - My second study - 2012-10-12.msg'
"" | out-file unknown-name.msg
ls * | % {
$match = [Regex]::Match($_.Name, '(?<Code>\d+) - (?<Symbol>.+) - (?<Name>.+) - (?<Date>\d{4}-\d{2}-\d{2}).msg')
[pscustomobject]@{
FullName = $_.Name;
Success = $match.Success;
Code = $match.Groups['Code'].Value;
Symbol = $match.Groups['Symbol'].Value;
Name = $match.Groups['Name'].Value;
Date = if ($match.Success) { [DateTime]::Parse($match.Groups['Date'].Value, [CultureInfo]::InvariantCulture) }
}
} | ft
所有名称均匹配,并显示正确的信息(包括转换为DateTime类型的日期):
FullName Success Code Symbol Name Date
-------- ------- ---- ------ ---- ----
01234 - Corres - Example title of my study - 2015-12-03.msg True 01234 Corres Example title of my study 2015-12-03 00:00:00
01234 - Word - My study - 2017-11-05.msg True 01234 Word My study 2017-11-05 00:00:00
12345 - Other Word - My second study - 2012-10-12.msg True 12345 Other Word My second study 2012-10-12 00:00:00
unknown-name.msg False