PowerShellで文字列置換をする方法はいくつかありますが、
ruby の String.gsub でブロックをとるパターン的なものがなかったので作ってみました。
# 動作環境
$PSVersionTable
Name Value
---- -----
PSVersion 5.1.17134.112
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.112
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
function Get-Gsub {
param([string]$pattern, [ScriptBlock]$block)
begin {
function reverse {
$arr = @($input)
[array]::reverse($arr)
$arr
}
}
Process {
$text = $_
$_ | select-string $pattern -AllMatches |
% { $_.matches } | reverse |
% {
$m = $_
$index = $m.index
$length = $m.length
$text = $text.remove($index, $length)
$ret = & $block($m)
$text = $text.insert($index, $ret)
}
$text
}
}
$text = @"
hello, world
hello, powershell
"@
$TextInfo = (Get-Culture).TextInfo
$text | Get-Gsub "\w+" {
$TextInfo.ToTitleCase($_.groups[0].value)
}
#=> Hello, World
#=> Hello, Powershell