user6496229
user6496229

Reputation:

Powershell, replace DOT with SPACE

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?

Upvotes: 4

Views: 24490

Answers (2)

luke
luke

Reputation: 4155

  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

Upvotes: 5

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

-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.

Upvotes: 7

Related Questions