Subtle differences replace() and -replace -eq diff output

This topic contains 4 replies, has 4 voices, and was last updated by  js 1 week, 1 day ago.

  • Author
    Posts
  • #98730

    Gnart
    Participant

    Appreciate an explanation in the subtle differences between "replace()" and -replace in the following code snippets, which yielded different results.
    replace() in code snippet A did not work.
    -replace() in code snippet B worked.

    # Snippet A
    foreach ($textLine in $fileContent) {
    	if ($textLine -like '*memsize*') {
    	    $textLine = $textLine.Replace('(\d+)','4096')
    	    $NewText += $textLine
    	}
    	else {
    		$NewText += $textLine
    	}
    }
    
    # Snippet B
    foreach ($textLine in $fileContent) {
    	if ($textLine -like '*memsize*') {
    	    $textLine = $textLine -Replace '(\d+)','4096'
    	    $NewText += $textLine
    	}
    	else {
    		$NewText += $textLine
    	}
    }
    
  • #98733

    Olaf Soyk
    Participant

    As far as I know the replace()-method does not work with regular expressions while the -replace operator does.

    • #98734

      Gnart
      Participant

      Thank you.

  • #98743

    postanote
    Participant

    Adding to Olaf's response.
    See the details here:

    PSTip A difference between the –replace operator and String.Replace method
    'powershellmagazine.com/2012/11/12/pstip-a-difference-between-the-replace-operator-and-string-replace-method'

    Comparing RegEx.Replace, String.Replace and StringBuilder.Replace – Which has better performance?
    'blogs.msdn.microsoft.com/debuggingtoolbox/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance'

  • #98914

    js
    Participant

    That's like .split() and -split. The first is a .net method of the String class, and the second is a powershell operator. The second can use regular expressions.

You must be logged in to reply to this topic.