.replace question

This topic contains 2 replies, has 2 voices, and was last updated by  Глеб Боушев 2 years ago.

  • Author
    Posts
  • #32710

    so i was doing something like this

    $regex = "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"

    Get-ChildItem $folder -Filter *.log | ForEach-Object {
    $newname = $folder + "\Parsed\parsed_" + $_.Name
    $content = [System.IO.File]::ReadAllText($_.FullName).replace($regex, "$& + text")

    and $content was not changed a bit

    while this worked fine:
    $regex = "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"

    Get-ChildItem $folder -Filter *.log | ForEach-Object {
    $newname = $folder + "\Parsed\parsed_" + $_.Name
    $content = [System.IO.File]::ReadAllText($_.FullName)
    $newcontent = [regex]::Replace($content, $regex, "$& text")

    and i cant really understand why? any ideas?
    Thanks in advance

  • #32713

    Dave Wyatt
    Moderator

    The String.Replace method has nothing to do with regular expressions. It's a straight text comparison. [regex]::Replace works, as does the -replace operator in PowerShell (which does use regex). This is where getting to know the .NET framework a bit will help:

    https://msdn.microsoft.com/en-us/library/system.string.replace%28v=vs.110%29.aspx

    $content = [System.IO.File]::ReadAllText($_.FullName) -replace $regex, "$& text"
    
  • #32714

    well, thanks! -..-

You must be logged in to reply to this topic.