19

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 Answers 2

29

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

1 Comment

But this solution also match for -content and replace it to &content.
21

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.

1 Comment

If you DO need your expressions inside double quotes, like when combining with $variables, you can escape the capture group dollar signs ($) by preceding them with a backtick (`)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.