0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

powershell、htmlタグライクな色変更

Posted at
Convert-ColorTextFromTags.ps1
function Convert-ColorTextFromTags {
    param(
        [Parameter(Mandatory=$true)]
        [string]$text  # インプット
    )
    # 正規表現パターンの定義
    $pattern = "<(?<color>red|blue|green|yellow|white|black|cyan|magenta)>(?<content>.*?)</\k<color>>"
    # デフォルト色の設定
    $defaultColor = "White"
    # 現在の位置を保持する変数
    $currentIndex = 0
    $raw_message = ""
    # テキストの中で色付きタグを検索
    foreach ($match in [regex]::Matches($text, $pattern)) {
        # マッチ開始位置までのデフォルト文字を出力
        if ($match.Index -gt $currentIndex) {
            $message = ($text.Substring($currentIndex, $match.Index - $currentIndex))
            $raw_message += $message;
            Write-Host $message -NoNewline -ForegroundColor $defaultColor
        }

        # タグの中の文字を指定された色で出力
        $color = $match.Groups["color"].Value
        $content = $match.Groups["content"].Value
        $raw_message += $content
        Write-Host $content -NoNewline -ForegroundColor $color

        # 現在の位置を更新
        $currentIndex = $match.Index + $match.Length
    }

    # 最後の部分のデフォルト文字を出力
    if ($currentIndex -lt $text.Length) {
        $message = ($text.Substring($currentIndex))
        $raw_message += $message;
        Write-Host $message -NoNewline -ForegroundColor $defaultColor
    }

    # 改行を追加
    Write-Host

    return $raw_message
}

# 関数の使用例
Convert-ColorTextFromTags "あまい<red>果実</red>貪る獣<blue>たち</blue>"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?