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

Welcome Forums General PowerShell Q&A Subtle differences replace() and -replace -eq diff output

This topic contains 4 replies, has 4 voices, and was last updated by

js
 
Participant
7 months, 4 weeks ago.

  • Author
    Posts
  • #98730

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 255
    Helping Hand
    Rank: Contributor

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

    • #98734

      Participant
      Points: 0
      Rank: Member

      Thank you.

  • #98743

    Participant
    Points: 316
    Helping Hand
    Rank: Contributor

    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
    Points: 316
    Helping Hand
    Rank: Contributor

    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.

The topic ‘Subtle differences replace() and -replace -eq diff output’ is closed to new replies.