RegEx basic

I have a big text file and need to replace this line:
DMGD819531229F~ (the last 2 fields are date of birth & gender…which change)
With this line:
DMG
D819531229F**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 = “DMGD819641019*M~”
$content -match “DMG*D8*(\d{8})*([MF])~”
$content.Replace(“DMG*D8*(\d{8})*([MF])~”,“DMG*D8*(\1)*(\2)**5:9~”)

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

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~

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:

'DMGD819641019M~’ -replace ‘~$’,‘**5:9~’
output:
DMGD819641019M**5:9~

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~