我想使用replace替换确切的单词,但我似乎不知道。

$value1 = "I brought tea for my team"

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

$value1 -replace $token, $newValue

实际结果:



预期结果:



固定:
$value1 = "I brought tea for my team"

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

$value1 -replace "\b$token\b", $newValue

最佳答案

@Theo是正确的。您可以使用正则表达式和单词边界\b来包装搜索词以仅匹配整个单词。

$value1 = "I brought tea for my team"

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

$value1 -replace "\b$token\b", $newValue

07-24 09:39