LoginSignup
0
0

More than 5 years have passed since last update.

powershell で ruby の String.gsub(pattern){|match| block} を作ってみた

Last updated at Posted at 2018-06-20

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
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