Search code examples
powershellreplacespecial-characters

Powershell How to remove specific characters within a text


Below is the text for which I want to remove specific characters

$testChars = '[{"user":"UserName1","date":"Fri, 15 Dec 2017 12:31:03 GMT","
    action":"Submitted","comment":"I have submitted for Approval"|
    "user":"UserName2","date":"Fri, 15 Dec 2017 13:14:21 GMT","action":"APPROVED","comme
    nt":"This has been approved......"|"user":"UserName1","date":"Fri, 15 Dec 2017 12:31:03 GMT","
    action":"Submitted","comment":"I have submitted for Approval"|"user":"UserName1","date":"Fri, 15 Dec 2017 12:31:03 GMT","
    action":"Submitted","comment":"This is rejected"}]'

From this string, I want to remove the below 6 characters

'
{ 
}
[
]
"

I want to retain all other text/symbols like colon and pipe symbol. I have tried below code, to replace the characters with empty"" but does not work for me:

 $newVal= $testChars -Replace "\[\{\}\]",""

Solution

  • Regex for character replacement:

    $newVal = $testChars -replace "\[|\]|\{|\}|`"|'"
    

    Simplified further using a set:

    $newVal = $testChars -replace '[[\]{}''"]'