Replace substring in PowerShell

前端 未结 2 396
后悔当初
后悔当初 2020-12-19 00:56

I have a string in the form -content-, and I would like to replace it with &content&. How can I do this with replace in PowerShell?

相关标签:
2条回答
  • 2020-12-19 01:18

    The built-in -replace operator allows you to use a regex for this e.g.:

    C:\PS> '-content-' -replace '-([^-]+)-', '&$1&'
    &content&
    

    Note the use of single quotes is essential on the replacement string so PowerShell doesn't interpret the $1 capture group.

    0 讨论(0)
  • 2020-12-19 01:21

    PowerShell strings are just .NET strings, so you can:

    PS> $x = '-foo-'
    PS> $x.Replace('-', '&')
    &foo&
    

    ...or:

    PS> $x = '-foo-'
    PS> $x.Replace('-foo-', '&bar&')
    &bar&
    

    Obviously, if you want to keep the result, assign it to another variable:

    PS> $y = $x.Replace($search, $replace)
    
    0 讨论(0)
提交回复
热议问题