0

How can I use string replacement to replace multiple, variable strings? I am currently doing it this way:

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

How can we do this with only one -replace statement?

3 Answers 3

3

Like this?

$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
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a list and a foreach loop. Then you only have to write it once.

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

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

$str

Comments

1

Here's the closest I could come up with (without defining a function specifically for the task:

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

Update

However if you're happy to go with a function, you could try something like this:

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" 

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.