Powershell: -replace does something .replace() will not

Created on 23 Aug 2018  路  3Comments  路  Source: PowerShell/PowerShell

Steps to reproduce

$str1='<a href="/bla/string">string</a>'
$str2=$1str -replace '<[^>]+>',''
$str3=$1str.replace('<[^>]+>','')

Expected behavior

$str2='string'
$str3='string'

Actual behavior

$str2='string'
$str3='<a href="/bla/string">string</a>'

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.14393.2430
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.2430
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
Issue-Question Resolution-Answered WG-Language

Most helpful comment

If any more clarity is required...

  • .Replace() is a string method build into the [string] data type by the .NET designers.
  • -replace is a string operator implemented by the PowerShell team utilising the [RegEx]::Replace() .NET method behind the scenes in order to give additional, easy to access functionality to PowerShell itself.

All 3 comments

@B-Art [string].Replace() just does simple string replacement. The -replace operator uses regular expressions like [regex]::replace().

If any more clarity is required...

  • .Replace() is a string method build into the [string] data type by the .NET designers.
  • -replace is a string operator implemented by the PowerShell team utilising the [RegEx]::Replace() .NET method behind the scenes in order to give additional, easy to access functionality to PowerShell itself.

Thanks for all your answers!

Was this page helpful?
0 / 5 - 0 ratings