如何在 Powershell 中转义反斜杠 [英] How to escape a backslash in Powershell

查看:64
本文介绍了如何在 Powershell 中转义反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 powershell 程序来使用

I'm writing a powershell program to replace strings using

-replace "$in", "$out"

它不适用于包含反斜杠的字符串,我该如何转义它?

It doesn't work for strings containing a backslash, how can I do to escape it?

推荐答案

-replace 运算符使用正则表达式,将反斜杠视为特殊字符.您可以使用双反斜杠来获得文字单反斜杠.

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

就您而言,由于您使用的是变量,因此我假设您在设计时不知道内容.在这种情况下,您应该通过 [RegEx]::Escape():

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.

这篇关于如何在 Powershell 中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆