match演算子
変数$Matchesでマッチした文字列を取得できる。要素0がマッチした文字列、要素1以降が部分マッチ(キャプチャ)された文字列になる。
ただし最初にマッチしたものしか得られないみたい。
PS C:\> "abcde" -match "(.)(.)" True PS C:\> $Matches Name Value ---- ----- 2 b 1 a 0 ab PS C:\> $Matches[0] ab
配列からマッチした要素を抜き出すこともできる様です。
PS C:\> @("one", "two", "three", "four", "five") -match "t"
two
three
regexオブジェクト
正規表現オブジェクトを使用するとマッチした全てが取得できる。
PS C:\> $re = New-Object regex("(.)(.)") # $re = [regex]"(.)(.)"でも可
PS C:\> $m = $re.Matches("abcde")
PS C:\> $m
Groups : {ab, a, b}
Success : True
Captures : {ab}
Index : 0
Length : 2
Value : ab
Groups : {cd, c, d}
Success : True
Captures : {cd}
Index : 2
Length : 2
Value : cd
PS C:\> $m[1].Groups[1]
Success : True
Captures : {c}
Index : 2
Length : 1
Value : c
PS C:\> $m[1].Groups[1].Value
c
後方参照
PS C:\> $re = new-object regex( "(\d)(\d)(\d)(\d)" )
PS C:\> $re.replace("1234", "`$4`$3`$2`$1")
4321