Replace substring in PowerShell

 ̄綄美尐妖づ 提交于 2020-01-10 04:48:07

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/14912948/replace-substring-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!