regex - 在 PowerShell 中转换文件字符串的正则表达式

标签 regex powershell

我有一些以以下结尾的 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/

相关文章:

powershell - Get-WinEvent 仅获取交互式登录消息

Powershell:输出文件

function - 自定义函数无法识别

java - 使用 powershell 系统用户映射的驱动器无法被其他人访问

powershell - 使用Powershell审核Exchange 2007邮箱的完全访问权限

Python 正则表达式提取日期

javascript - 在 JavaScript 中查找文本字符串

regex - 在 Lua 5.1 中将可重复字符串匹配为 "whole word"

regex - 如何编写更易于维护的正则表达式?

python - 为什么我在正则表达式模式中需要一个额外的空间才能使其正常工作?