【问题标题】:Powershell, replace DOT with SPACEPowershell,用 SPACE 替换 DOT
【发布时间】:2017-08-22 01:21:05
【问题描述】:

这行得通:

$string = "This string, has a, lot, of commas in, it."
  $string -replace ',',''

输出:这个字符串中有很多逗号。

但这不起作用:

$string = "This string. has a. lot. of dots in. it."
  $string -replace '.',''

输出:空白。

为什么?

【问题讨论】:

标签: powershell character-replacement


【解决方案1】:

-replace 使用正则表达式 (regexp) 进行搜索,而在正则表达式中,点是一个特殊字符。使用'\'转义它,它应该可以工作。见Get-Help about_Regular_Expressions

【讨论】:

    【解决方案2】:
    1. -replace 中的第一个参数是正则表达式(但第二个不是)
      '.' 是正则表达式中的特殊字符,表示每个字符
      $string -replace '.', '' 表示:替换每个带有'' 的单个字符(空白字符)
      结果你得到空白字符串
      因此,为了转义正则表达式特殊字符 . 并将其视为普通字符,您必须使用 \
      $string -replace '\.', '' 对其进行转义
    2. 如果您想稍后重用字符串,则必须将其重写为变量,否则结果将丢失
      $string = $string -replace '\.', ''

    应该是这样的:

    $string = "This string. has a. lot. of dots in. it."
    $string = $string -replace '\.', ''
    

    然后

    echo $string

    结果:

    This string has a lot of dots in it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2016-08-12
      • 1970-01-01
      • 2012-03-10
      • 2020-07-17
      • 1970-01-01
      • 2015-10-25
      • 2013-10-08
      相关资源
      最近更新 更多