Aesthetically pleasing string replaces expression

I currently have code that looks like this:

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

I would like to format it as follows:

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

so replace statements are stacked on top of each other.

I could use backtic as a line continuation character, but other stackoverflow related questions explain why this 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 steam does not match.

There are several replacement statements in my actual code (not just two).

+4
source share
5 answers

If you have many replacements, then about another approach, which allows much more opportunities for aligning pairs, replacing beautifully, without affecting the replacement code block.

$onestr = 'one thing uno thing'


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

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

$onestr
+2

, , , , , , - PowerShell PowerShell .Net.

$onestr = 'one thing uno thing'

$onestr.
    Replace('one', 'two').
    Replace('uno', 'dos')
+2

` , :

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

, , , , , :

$onestr = $twostr -replace "one","two" <#
               #> -replace "uno","dos" <#
               #> -replace "foo","bar"

, DRY er, !


:.NET Regex.Replace , :

function translate(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [string]$text,

    [Parameter(Mandatory=$true)]
    [hashtable]$map,

    [switch]$caseSensitive
) {
    $options = if ([bool]$caseSensitive) { '' } else { '(?i)' }
    ([regex]($options +
         ($map.Keys -replace '[$^*?.+|()\[\]{}\\]', '\$&' -join '|')
    )).Replace($text, { param([string]$match) $map[$match] })
}

'Abc' | translate -map @{
    'a'='1'
    'b'='2'
    'c'='3'
}

-INsensitive.

+1

metafunction [scriptblock], - . , ConvertTo-Spanish Invoke-Unwrap : *

function Invoke-Unwrap( [scriptblock]$sb) {
    Invoke-Expression ($sb -replace '\r?\n\s*-', ' -')
}

Invoke-Unwrap {
    function script:ConvertTo-Spanish( [string]$str ) { 
        $str 
            -replace "one","uno"
            -replace "two","dos" 
            -replace "thing","lo"
    }
}

ConvertTo-Spanish "thing one and thing two"

Invoke-Unwrap , , "-". , - , , . ($sb -replace '\r?\n\s*([-+*/])', ' $1').

, , , Invoke-Expression, , , , - , SED.

  • Apologies for my limited knowledge of Spanish ... :-)
+1
source

Source: https://habr.com/ru/post/1654064/


All Articles