RegEx basic

This topic contains 4 replies, has 3 voices, and was last updated by  js 3 weeks ago.

  • Author
    Posts
  • #103522

    Kevin Sexton
    Participant

    I have a big text file and need to replace this line:
    DMG*D8*19531229*F~ (the last 2 fields are date of birth & gender...which change)
    With this line:
    DMG*D8*19531229*F**5:9~
    This is what I have so far but it does NOT work. No error.

    $content = [System.IO.File]::ReadAllText("C:\downloads\dmgLines.txt").Replace("DMG\*D8\*(\d{8})\*([MF])~","DMG\*D8\*(\1)\*(\2)\*\*5:9~")
    [System.IO.File]::WriteAllText("C:\downloads\dmgNewLines.txt", $content)
    

    I can find the string but my replace does nothing:

    
    $content = "DMG*D8*19641019*M~"
    $content -match "DMG\*D8\*(\d{8})\*([MF])~"
    $content.Replace("DMG\*D8\*(\d{8})\*([MF])~","DMG\*D8\*(\1)\*(\2)\*\*5:9~")
    
  • #103523

    Olaf Soyk
    Participant

    As far as I remeber the .replace() method does not work with regular expressions. You should use the original Powershell -replace statement instead.

  • #103525

    Kevin Sexton
    Participant

    Thanks Olaf. I have switched to -replace but it is still not working.

    (Get-Content -path "C:\downloads\dmgLines.txt") `
        -replace "DMG\*D8\*(\d{8})\*([MF])~","DMG\*D8\*$1\*$2\*\*5:9~" |    Out-File C:\downloads\dmgNewLines.txt
    
    #It is easier to see the problem this way. I think the problem is with my quotes. 
    
    $content = "DMG*D8*19641019*M~"
    $content    -replace '"DMG\*D8\*(\d{8})\*([MF])~"',"DMG\*D8\*$1\*$2\*\*5:9~"
    #output: DMG*D8*19641019*M~
    
    • #103528

      Olaf Soyk
      Participant

      Am I wrong or do you try to replace the last tilde in the line with something before the tilde plus the tilde? If yes – this could be a solution:

      'DMG*D8*19641019*M~' -replace '~$','**5:9~'

      output:

      DMG*D8*19641019*M**5:9~
    • #103529

      js
      Participant

      No '\*' regex in the 2nd -replace argument needed. Use single quotes so powershell doesn't try to interpret the $1 and $2 variables. I like http://regex101.com to test regular expressions. Don't have to quote the first argument twice.

      $content = "DMG*D8*19641019*M~"
      $content -replace "DMG\*D8\*(\d{8})\*([MF])~", 'DMG*D8*$1*$2**5:9~'
      
      DMG*D8*19641019*M**5:9~
      

You must be logged in to reply to this topic.