3

I want to replace the exact word using replace but I can't seem to figure out.

$value1 = "I brought tea for my team"

$newValue = "coffee"
$token = "tea"

$value1 -replace $token, $newValue

Actual Result:

I brought coffee for my coffeem

Expected result:

I brought coffee for my team

Fix:

$value1 = "I brought tea for my team"

$newValue = "coffee"
$token = "tea"

$value1 -replace "\b$token\b", $newValue
3
  • does the search string always appear in the middle of the string, separated by spaces? (e.g. not I brought tea, tea was what I brought, I brought "tea" for my team) Commented Sep 9, 2019 at 19:18
  • 3
    Try -replace "\b$token\b", $newvalue Commented Sep 9, 2019 at 19:21
  • Thank you Theo! works great! Commented Sep 9, 2019 at 19:31

3 Answers 3

6

@Theo is correct. You can use regular expressions and the Word Boundary \b to wrap your search term to only match whole words.

$value1 = "I brought tea for my team"

$newValue = "coffee"
$token = "tea"

$value1 -replace "\b$token\b", $newValue
Sign up to request clarification or add additional context in comments.

4 Comments

I don't get it, why use variables at all, why not just use $value1 -replace "\btea\b", "coffee" ? By mixing constructs with variables \b$token\b you pretend to know what a $token is...
@sln, $token is defined in the original post. The question is also tagged PowerShell. It makes sense to anyone who knows PowerShell. The original post was also using variables for matching and replacement. Why not have the answer follow the original idea? It shows the flexibility of the language.
@AdminOfThings - What ? Language flexibility ? if $value1 = "I brought -'tea' for my team" and if $newValue = "coffee" and $token = "-'tea'" or even $token = "tea" won't match. I thought it was a regex question ?
"I want to replace the exact word using replace" + "Expected result" should answer your question, @sin =)
2

Just like Theo mentioned on the comments...

λ  $value1 = "I brought tea for my team"
λ  $newValue = "coffee"
λ  $token = "tea"
λ  $value1 -replace $token, $newValue
I brought coffee for my coffeem

λ  $value1 -replace "\b$token\b", $newValue
I brought coffee for my team

You need to set boundaries. Even if you're not a city.

Comments

0

You can use the following:

$token = " tea "
$newValue = " coffee "

1 Comment

You can, but you'd be altering the variables values, instead of using replace to solve the problem, which seems to be the point here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.