4

This works:

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

Output: This string has a lot of commas in it.

But this doesn't work:

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

Output: blank.

Why?

2 Answers2

7

-replace searches using regular expressions (regexp), and in regexps the dot is a special character. Escape it using '\', and it should work. See Get-Help about_Regular_Expressions.

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33
5
  1. The first argument in -replace is a regular expression (but the second one is not)
    '.' is a special char in regular expressions and means every single character
    $string -replace '.', '' means: replace every single character with '' (blank char)
    and in the result you get blank string
    So in order to escape regular expression special char . and make it treated as a normal character you have to escape it using \
    $string -replace '\.', ''
  2. If you want to reuse your string later you have to rewrite it to a variable otherwise the result will be lost
    $string = $string -replace '\.', ''

So it should be:

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

and then

echo $string

results in:

This string has a lot of dots in it

luke
  • 3,435
  • 33
  • 41