Powershell,用空格替换 DOT

4 powershell character-replacement

这有效:

$string = "This string, has a, lot, of commas in, it."
  $string -replace ',',''
Run Code Online (Sandbox Code Playgroud)

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

但这不起作用:

$string = "This string. has a. lot. of dots in. it."
  $string -replace '.',''
Run Code Online (Sandbox Code Playgroud)

输出:空白。

为什么?

Jef*_*lin 6

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


luk*_*uke 5

  1. 第一个参数-replace是正则表达式(但第二个参数不是)
    '.'是正则表达式中的特殊字符,表示每个字符的意思
    $string -replace '.', ''是:将每个字符替换为''(空白字符)
    ,结果中会得到空白字符串
    所以按顺序要转义正则表达式特殊字符.并将其视为普通字符,您必须使用转义它\
    $string -replace '\.', ''
  2. 如果您想稍后重用字符串,则必须将其重写为变量,否则结果将丢失
    $string = $string -replace '\.', ''

所以应该是:

$string = "This string. has a. lot. of dots in. it."
$string = $string -replace '\.', ''
Run Code Online (Sandbox Code Playgroud)

进而

echo $string

结果是:

This string has a lot of dots in it