Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aesthetically Pleasing String Replace Statement

Tags:

powershell

I currently have code that looks like this:

$onestr = $twostr -replace "one","two" -replace "uno","dos"

I would like to format it like this:

$onestr = $twostr -replace "one","two" 
                  -replace "uno","dos"

such that the replace statements stack on top of each other.

I could use backtic as the line continuation character, but other stackoverflow questions cover why that is not a good idea.

I tried code that looks like this:

$onestr = ($twostr -replace "one","two" 
                   -replace "uno","dos"
          )

But I got an error that the paren is not matched.

My actual code has several replace statements (not just two).

like image 704
Be Kind To New Users Avatar asked Mar 12 '23 04:03

Be Kind To New Users


1 Answers

If you have a lot of replacements, what about a different approach which allows much more scope for the aligning of the replacement pairs nicely, without affecting the block of replace code.

$onestr = 'one thing uno thing'


$Pairs = @{ 
    'one' = 'two'
    'uno' = 'dos'
}

$Pairs.GetEnumerator() | ForEach-Object { 
    $onestr = $onestr -replace $_.Name, $_.Value
}

$onestr
like image 108
TessellatingHeckler Avatar answered Mar 21 '23 06:03

TessellatingHeckler