Kev*_*vin 4 regex format console powershell
这是一个技术问题,但作为练习,我的目的是编写一个PS来接受管道输入,以正则表达式作为参数,并突出显示与正则表达式匹配的任何文本.
我无法找到任何信息的部分是,文本匹配,捕获到缓冲区或替换文本很容易.但我需要用颜色控件替换匹配的文本,原始文本,然后恢复以前的颜色.我似乎找不到任何方法来生成除写入输出之外的颜色输出,并且不能在单次写入中执行单独的颜色,这意味着:
匹配正则表达式
-write-host输出匹配前的所有文本,默认颜色为-NoNewLine
-write-host匹配,使用-NoNewLine
-write-host剩余部分
这看起来很混乱,如果我们想支持多场比赛,会变得更加混乱.有没有更有说服力的方法来做到这一点?
Write-Host是这样做的正确方法.使用结果对象的.Index和.Length属性Match来确定匹配文本的确切位置.你只需要小心跟踪索引:)
这适用于多个匹配,并不是非常不整洁的IMO:
function ColorMatch
{
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string] $InputObject,
[Parameter(Mandatory = $true, Position = 0)]
[string] $Pattern
)
begin{ $r = [regex]$Pattern }
process
{
$ms = $r.Matches($inputObject)
$startIndex = 0
foreach($m in $ms)
{
$nonMatchLength = $m.Index - $startIndex
Write-Host $inputObject.Substring($startIndex, $nonMatchLength) -NoNew
Write-Host $m.Value -Back DarkRed -NoNew
$startIndex = $m.Index + $m.Length
}
if($startIndex -lt $inputObject.Length)
{
Write-Host $inputObject.Substring($startIndex) -NoNew
}
Write-Host
}
}
Run Code Online (Sandbox Code Playgroud)