【发布时间】:2020-01-11 13:33:17
【问题描述】:
我想使用 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
【问题讨论】:
-
搜索字符串是否总是出现在字符串的中间,用空格隔开? (例如不是
I brought tea、tea was what I brought、I brought "tea" for my team) -
试试
-replace "\b$token\b", $newvalue -
谢谢西奥!效果很好!
标签: regex powershell replace