我有以下代码:
$BuildDetails = Get-Content "d:\BuildDetails.txt"
[regex]$BuildDetailsRY = '\bRY:\s+\K\S+'
[regex]$BuildDetailsRoY = '\bRoY:\s+\K\S+'
[regex]$BuildDetailsSP = '\bSP:\s+\K\S+'
[regex]$BuildDetailsRC = '\bRC:\s+\K\S+'
[regex]$BuildDetailsBranch = '\bBranch:\s+\K\S+'
$ReleaseYear = $BuildDetails | Select-String $BuildDetailsRY -AllMatches | Foreach-Object {$_.Matches} |
Foreach-Object {$_.Groups[2].Value}
Write-Host Release Year = $ReleaseYear
当我运行它时,我收到以下错误: 无法转换价值" \ bSP:\ s + \ K \ S +"输入" System.Text.RegularExpressions.Regex"。错误:"解析" \ bSP:\ s + \ K \ S +" - 无法识别的转义序列\ K。"
这是它正在查找的文本文件。
RY: 17
RoY: 2
SP: 0
RC: 1
Branch: $/Release/17.2.x
我希望REGEX做的是在标题后找到数据,例如17
答案 0 :(得分:0)
我最终找到了一个更好的方法:
$BuildDetails = Get-Content "D:\BuildDetails.txt"
[regex]$BuildDetailsRY = '(?<=RY: ).*?(?=\s)'
[regex]$BuildDetailsRoY = '(?<=RoY: ).*?(?=\s)'
[regex]$BuildDetailsSP = '(?<=SP: ).*?(?=\s)'
[regex]$BuildDetailsRC = '(?<=RC: ).*?(?=\s)'
[regex]$BuildDetailsBranch = '(?<=Branch: ).*'
$ReleaseYear = [regex]::matches($BuildDetails, $BuildDetailsRY)
$ReleaseofYear = [regex]::matches($BuildDetails, $BuildDetailsRoY)
$SP = [regex]::matches($BuildDetails, $BuildDetailsSP)
$RC = [regex]::matches($BuildDetails, $BuildDetailsRC)
$Branch = [regex]::matches($BuildDetails, $BuildDetailsBranch)