regex - 对 Get-Help 输出 : how to use Regex to select exact string that starts with a hyphen(-) and ends with an alphabet 进行着色

标签 regex powershell replace ascii regexp-replace

我目前正在尝试为 PowerShell 的 Get-Help cmdlet 输出着色。我成功地对显示我尝试使用 Get-Help 的 cmdlet 名称的输出进行了着色。我还设法对显示手册页所有标题的输出进行着色。但是,我无法对手册页上显示的选项的输出进行一致的着色,如下所示:

#!/usr/bin/env powershell

$GREEN = "$([char]0x1b)[92m"
$RED = "$([char]0x1b)[91m"
$CYAN = "$([char]0x1b)[96m"
$BLUE = "$([char]0x1b)[94m" 
$YELLOW = "$([char]0x1b)[93m" 
$PURPLE = "$([char]0x1b)[95m" 
$RESET = "$([char]0x1b)[0m"

 
Get-Help @args > man_text.txt
$WORD = $args[0]

cat man_text.txt | `
    % {$_ `
         -creplace "^[A-Z \d\W]+$", "$GREEN`$0$RESET" `
         -creplace "\b$WORD\b", "$YELLOW`$0$RESET" `
         -replace "-[a-z]*\b", "$CYAN`$0$RESET" `
    }

enter image description here

换句话说,我需要匹配以“-”开头并以字母表结尾的字符串的正则表达式。

如果有人能帮助我解决这个问题,我将非常感激。提前致谢。

最佳答案

您可以将其放入 $Profile 文件中,以自动为 Get-Help 的输出着色。它修复了使用 RegEx \B-\w+ 对参数进行着色的问题(请参阅 regex101 demo )。

# Overrides the original Get-Help command to colorize its output.

Function Get-Help {
    [CmdletBinding(DefaultParameterSetName='AllUsersView', HelpUri='https://go.microsoft.com/fwlink/?LinkID=2096483')]
    param(
        [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [string] ${Name},

        [string] ${Path},

        [ValidateSet('Alias','Cmdlet','Provider','General','FAQ','Glossary','HelpFile','ScriptCommand','Function','Filter','ExternalScript','All','DefaultHelp','DscResource','Class','Configuration')]
        [string[]] ${Category},

        [Parameter(ParameterSetName='DetailedView', Mandatory=$true)]
        [switch] ${Detailed},

        [Parameter(ParameterSetName='AllUsersView')]
        [switch] ${Full},

        [Parameter(ParameterSetName='Examples', Mandatory=$true)]
        [switch] ${Examples},

        [Parameter(ParameterSetName='Parameters', Mandatory=$true)]
        [string[]] ${Parameter},

        [string[]] ${Component},

        [string[]] ${Functionality},

        [string[]] ${Role},

        [Parameter(ParameterSetName='Online', Mandatory=$true)]
        [switch] ${Online},

        [Parameter(ParameterSetName='ShowWindow', Mandatory=$true)]
        [switch] ${ShowWindow}
    )

    process {
        # Call the original Get-Help command by its fully qualified path.
        $help = Microsoft.PowerShell.Core\Get-Help @PSBoundParameters

        # Define the styles for colorization.
        $style = @{
            SECTION = $PSStyle.Formatting.FormatAccent
            COMMAND = $PSStyle.Foreground.BrightYellow
            PARAM   = $PSStyle.Foreground.FromRgb(64,200,230)
        }

        # Escape the command name for use in RegEx
        $commandNameEscaped = [regex]::Escape( $help.Name )

        # Define a RegEx for doing the formatting. The names of the RegEx groups have to match the keys of the $style hashtable.
        $regEx = @(
            "(?m)(?<=^[ \t]*)(?<SECTION>[A-Z][A-Z \t\d\W]+$)"
            "(?<COMMAND>\b$commandNameEscaped\b)"
            "(?<PARAM>\B-\w+)"
        ) -join '|'

        # Format the help object
        $help | Out-String | ForEach-Object {
            [regex]::Replace( $_, $regEx, {  
                # Get the RegEx group that has matched.
                $matchGroup = $args.Groups.Where{ $_.Success }[ 1 ]
                # Use the RegEx group name to select associated style for colorizing the match.
                $style[ $matchGroup.Name ] + $matchGroup.Value + $PSStyle.Reset
            })
        }
    }
}

输出:

Console Output

备注:

  • 通过定义与现有命令同名的函数,我们可以有效地覆盖它。
  • 我们可以通过指定其完全限定名称来调用原始命令,模块前缀如 Microsoft.PowerShell.Core\Get-Help。要获取模块前缀,请键入 (Get-Command TheCommand).ModuleName
  • 使用自动 $PSStyle 变量作为获取用于着色的 ANSI 转义码的便捷方法。
  • 当我们调用带有 -? 参数的命令时,这甚至可以工作,因为这会在内部调用 Get-Help
  • 完整模式的演示和解释位于 regex101 .
  • 需要PS 7.2+

关于regex - 对 Get-Help 输出 : how to use Regex to select exact string that starts with a hyphen(-) and ends with an alphabet 进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72525108/

相关文章:

powershell - 如何使用 PowerShell 从 MSMQ 消息队列中删除特定消息

email - 使用 "Send"参数调用 "1"的 PowerShell 异常 : "Failure sending mail."

jquery - 如何使用 jQuery 从每个选择选项中删除文本

C# 替换字符串中的字符串

regex - 在文件中搜索RegEx字符串,仅返回文件名,路径和字符串

JavaScript:如何从字符串中查找和检索数字

powershell cmdlet 如何将信息或错误通过管道传输到 write-eventlog

python - Python中删除多列中的非中文元素

javascript - 在字符第一次出现时停止匹配,或继续

linux - 用于递归查找和替换的 Sed 命令失败