我有一些以以下结尾的 zip 文件:
Some nameA 1.0.0 rev. 110706.zip
Some nameB 1.0.0 rev. 110806.zip
Some name moreC 1.0 rev. 120904.zip
name 1.1 rev. 130804.zip
在 PowerShell 中,我想读取这些文件名,创建一个仅包含版本但转换为以下格式的新文本文件:
1.0.0.110706
1.0.0.110806
1.0.120904
1.1.130804
现在我这样做:
$files = Get-ChildItem "." -Filter *.zip
for ($i=0; $i -lt $files.Count; $i++) {
$FileName = $files[$i].Name
$strReplace = [regex]::replace($FileName, " rev. ", ".")
$start = $strReplace.LastIndexOf(" ")
$end = $strReplace.LastIndexOf(".")
$length = $end-$start
$temp = $strReplace.Substring($start+1,$length-1)
$temp
}
我看过: Use Powershell to replace subsection of regex result
看看我是否可以获得更紧凑的版本。对上述模式有什么建议吗?
最佳答案
您可以执行单个 -replace
操作:
$FileName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'
分割:
^\D+ # 1 or more non-digits - matches ie. "Some nameA "
([\.\d]+) # 1 or more dots or digits, capture group - matches the version
\srev\.\s # 1 whitespace, the characters r, e and v, a dot and another whitespace
(\d+) # 1 or more digits, capture group - matches the revision number
在第二个参数中,我们用 $1
和 $2
引用两个捕获组
您可以通过管道将 Get-ChildItem
传递给 ForEach-Object
而不是使用 for
循环并索引到 $files
:
Get-ChildItem . *.zip |ForEach-Object {
$_.BaseName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'
} | Out-File output.txt
关于regex - 在 PowerShell 中转换文件字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202205/