I would like to color highlight sections of a pipeline string according to a regex in Powershell
Write-Host
is the right way to do this. Use the .Index
and .Length
properties of the resulting Match
object to determine where exactly the matched text is. You just need to be a bit careful keeping track of indices :)
This works for multiple matches, and is not terribly untidy 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
}
}