【问题标题】:Powershell replace only exact match stringPowershell 仅替换完全匹配的字符串
【发布时间】: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 teatea was what I broughtI brought "tea" for my team
  • 试试-replace "\b$token\b", $newvalue
  • 谢谢西奥!效果很好!

标签: regex powershell replace


【解决方案1】:

您可以使用以下内容:

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

【讨论】:

  • 你可以,但你会改变变量值,而不是使用替换来解决问题,这似乎是这里的重点
【解决方案2】:

就像在 cmets 上提到的 Theo...

λ  $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

您需要设定界限。即使你不是一个城市。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 我不明白,为什么要使用变量,为什么不直接使用 $value1 -replace "\btea\b", "coffee" ?通过将构造与变量 \b$token\b 混合在一起,您假装知道 $token 是什么...
    • @sln, $token 是在原帖中定义的。该问题也被标记为 PowerShell。这对任何了解 PowerShell 的人来说都是有意义的。原始帖子还使用变量进行匹配和替换。为什么不让答案遵循最初的想法?它显示了语言的灵活性。
    • @AdminOfThings - 什么?语言灵活性 ?如果$value1 = "I brought -'tea' for my team"$newValue = "coffee"$token = "-'tea'" 甚至$token = "tea" 将不匹配。我以为这是一个正则表达式问题?
    • “我想用替换替换确切的单词”+“预期结果”应该回答你的问题,@sin =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多