I would like to color highlight sections of a pipeline string according to a regex in Powershell

Question:

This is a question of technique, but as an exercise my intention is to write a PS to accept piped input, with a regex as a parameter, and highlight any text matching the regex.

The part I’m not able to find any info on is that it’s easy to match text, capturing to a buffer, or to replace text. But I need to replace matched text with color control, the original text, then resume the previous color. I can’t seem to find any way to generate color output other than with write-output, and can’t do separate colors in a single write, which would mean:

-matching the regex

-write-host out all text prior to the match in default color, with -NoNewLine

-write-host the match, with -NoNewLine

-write-host the remainder

This seems messy, and gets even more messy if we want to support multiple matches.
Is there a more eloquent way to do this?

Answer:

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:

Source:

I would like to color highlight sections of a pipeline string according to a regex in Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply