用一个替换表达式替换许多变量字符串

时间:2015-03-09 23:19:36

标签: powershell powershell-v4.0

如何使用字符串替换来替换多个可变字符串?我目前正在这样做:

 > $a = "a"
 > $b = "b"
 > $c = "c"
 > $d = "d"
 > $e = "e"
 > $f = "f"
 > $g = "g" 
 > "abcdefg" -replace $a -replace $b -replace $c -replace $d -replace $e -replace $f -replace $g 

我们如何只使用一个-replace语句来完成此操作?

3 个答案:

答案 0 :(得分:3)

喜欢这个吗?

$a = "a"
 $b = "b"
 $c = "c"
 $d = "d"
 $e = "e"
 $f = "f"
 $g = "g" 

 $regex = $a,$b,$c,$d,$e,$f,$g -join '|'

  "abcdefg" -replace $regex

答案 1 :(得分:1)

您可以使用列表和foreach循环。然后你只需要写一次。

$str = 'abcdefg'
$replacements = $a,$b,$c,$d,$e,$f,$g

foreach ($r in $replacements) {
  $str = $str -replace $r
}

$str

答案 2 :(得分:1)

这里是我能提出的最接近的(没有专门为这项任务定义一个功能:

cls
$replacements = @(@("a","z"),@("b","y"),@("c","x"))
$text = "abcdef"
$replacements | %{$text = $text -replace $_[0],$_[1]; $text} | select -last 1

<强>更新

但是如果你很乐意使用某个功能,你可以试试这样的事情:

cls

function Replace-Strings
{
    [CmdletBinding()]
    param
    (

        [Parameter(Mandatory=$True,ValueFromPipeline=$true,Position=1)]
        [string] $string

        ,[Parameter(Mandatory=$True,Position=2)]
        [string[]] $oldStrings

        ,[Parameter(Mandatory=$false,Position=3)]
        [string[]] $newStrings = @("")
    )
    begin
    {
        if ($newStrings.Length -eq 0) {$newStrings = "";}
        $i = 0
        $replacements = $oldStrings | %{Write-Output @{0=$_;1=$newStrings[$i]}; $i = ++$i % $newStrings.Length;}
    }
    process
    {
        $replacements | %{ $string = $string -replace $_[0], $_[1]; $string } | select -last 1
    }

}

#A few examples
Replace-Strings -string "1234567890" -oldStrings "3" 
Replace-Strings -string "1234567890" -oldStrings "3" -newStrings "a" 
Replace-Strings -string "1234567890" -oldStrings "3","5" 
Replace-Strings -string "1234567890" -oldStrings "3","5" -newStrings "a","b"
Replace-Strings -string "1234567890" -oldStrings "1","4","5","6","9" -newStrings "a","b"

#Same example using positional parameters
Replace-Strings -string "1234567890" "1","4","5","6","9" "a","b"

#or you can take the value from the pipeline (you must use named parameters if doing thi)
"1234567890" | Replace-Strings  -oldStrings "3"
"1234567890","123123" | Replace-Strings -oldStrings "3"
"1234567890","1234123" | Replace-Strings -oldStrings "3","4","1" -newStrings "X","Y" 

输出:

124567890
12a4567890
12467890
12a4b67890
a23bab78a0
a23bab78a0
124567890
124567890
1212
X2XY567890
X2XYX2X