简体   繁体   中英

Escape Tilde in Powershell Replace

I am working on a powershell script to parse a file into a different delimited format that can easily be loaded into Excel or a DB.

I've gotten it mostly figured except for finding and replacing the string "~S~|" where all characters should be taken literal.

I've tried the following to no avail: "\\~S\\~\\|" "~S~\\|" "~S~|" <-- this one is squirrely since | is or in RegEx land

Any suggestions would be helpful.

The regex.escape method is designed for this kind of situations where you don't know which characters are considered special (meta characters).

PS> [regex]::escape("~S~|")
~S~\|

You can see that the only meta character is the pipe sign (eg '|') and that the escape method escaped it for you (added a backslash in front of it).

PS> "this~S~|is~S~|a~S~|dog" -replace [regex]::escape('~S~|')
thisisadog

can you try this :

$string = "this~S~|is~S~|a~S~|dog"
$string -replace '~S~\|',' '

I was able to get around this with a work around. Thank you for all your input, all answers work as you described.

In order for me to get this to work in a very long string with multiple instances of the 'find' value I ended up having to build the string as it grew.

For example:

$tString = $_
$tString = $tString -replace 'Name:', ''
$tString = $tString -replace 'Id:', ''
$tString = $tString -replace 'Administrative group:', ''
$tString = $tString -replace 'Administrative class\(es\):', ''
$tString = $tString -replace 'Primary group:', ''
$tString = $tString -replace 'Session group:', ''
$tString = $tString -replace '~S~([^-]+)\|', '$1|'
$tString = $tString -replace ';\|', ';'
return $tString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM