这有效:
$string = "This string, has a, lot, of commas in, it."
$string -replace ',',''
输出:这个字符串中有很多逗号。
但这不起作用:
$string = "This string. has a. lot. of dots in. it."
$string -replace '.',''
输出:空白。
为什么?
这有效:
$string = "This string, has a, lot, of commas in, it."
$string -replace ',',''
输出:这个字符串中有很多逗号。
但这不起作用:
$string = "This string. has a. lot. of dots in. it."
$string -replace '.',''
输出:空白。
为什么?
-replace使用正则表达式 (regexp) 进行搜索,在正则表达式中,点是一个特殊字符。使用''转义它\,它应该可以工作。见Get-Help about_Regular_Expressions。
-replace是正则表达式(但第二个不是)'.'是正则表达式中的特殊字符,表示每个字符的意思是:用(blank char)$string -replace '.', ''替换每个字符,
结果得到空白字符串
所以按顺序要转义正则表达式特殊字符并将其视为普通字符,您必须使用''.\$string -replace '\.', ''$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