简体   繁体   English

如何使用c#中的regex.replace用反斜杠替换单个字符?

[英]How do you replace a single character with a backslash using regex.replace in c#

If I do this: 如果我这样做:

Regex.Replace("unlocktheinbox.com", "[t]", "\\$&");

My result is: 我的结果是:

"unlock\\theinbox.com"

I'm expecting it to be 我期待它

"unlock\theinbox.com"

I'm trying to replace "t" with "\\t" using regex.replace. 我正在尝试使用regex.replace将“t”替换为“\\ t”。 I made this example very basic to explain what I'm trying to accomplish. 我让这个例子非常基本来解释我想要完成的事情。

Try following 试试以下

var result = Regex.Replace("unlocktheinbox.com", "[t]", @"\");

Note that, if you observe result while debugging via hovering mouse on result . 需要注意的是,如果你观察result ,同时通过对鼠标悬停调试result it will look like unlock\\\\theinbox.com because \\ is escaped. 它看起来像unlock\\\\theinbox.com因为\\被转义。 But actually, if you print result or use anywhere it will be unlock\\theinbox.com 但实际上,如果您打印result或在任何地方使用它将unlock\\theinbox.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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