How to escape a backslash in Powershell

前端 未结 2 1473
Happy的楠姐
Happy的楠姐 2020-12-11 04:47

I\'m writing a powershell program to replace strings using

-replace \"$in\", \"$out\"

It doesn\'t work for strings containing a backslash,

2条回答
  •  醉酒成梦
    2020-12-11 05:08

    The -replace operator uses regular expressions, which treat backslash as a special character. You can use double backslash to get a literal single backslash.

    In your case, since you're using variables, I assume that you won't know the contents at design time. In this case, you should run it through [RegEx]::Escape():

    -replace [RegEx]::Escape($in), "$out"
    

    That method escapes any characters that are special to regex with whatever is needed to make them a literal match (other special characters include .,$,^,(),[], and more.

提交回复
热议问题