Search code examples
powershellpowershell-3.0

replace regex value in powershell


  1. From the below line: [1;32mget[0m /dir/dir/dir {} [oiid:197,uiid:7522] [32m200[0m (676ms)
  2. convert it to: get /dir/dir/dir {} [oiid:197,uiid:7522] 200 (676ms)
  3. any suggestions on regex please the value 200 can be any number and the value get can be any http method.
  4. I have tried
            $_.replace("[[\d+m]","").replace('[[1;\d+m]',"").replace('[[\d+]m]',"")
         } | Set-Content $newfilepath```

Solution

  • You can do the following using -replace operator and a regex:

    $string = '[1;32mget[0m /dir/dir/dir {} [oiid:197,uiid:7522] [32m200[0m (676ms)'
    $string -replace '\[\d.*?m'
    

    \[ matches [ and note that it needs to be escaped for literal match because [ is special to regex. \d is a digit. .*? matches as few characters as possible until m is matched.

    The String class Replace() method does not support regex. So you cannot use regex expressions like \d inside.