替换(在模式结束时解析"\"非法)

Mr.*_*eto 2 c#

好吧,我有一个C#的迷你程序,所以我在我的程序中这样做

wordSearch = "T:\\"
wordReplace = "T:\\Gestion\\"
content = Regex.Replace(content, wordSearch, wordReplace);
Run Code Online (Sandbox Code Playgroud)

但是不起作用.错误是:

parsing "T:\" - illegal \ at end of pattern.
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

[添加]

抱歉! 也许我没有解释清楚.所以我再试一次.

我做了一个输入字符串的表单,但是如果这个字符串是"T:\",则程序取"T:\".所以,我将这个字符串保存在变量"workShearch"中.

在此变量用于:

content = Regex.Replace(content, Regex.Escape(wordSearch), Regex.Escape(wordReplace));
Run Code Online (Sandbox Code Playgroud)

但是这一行包含一个错误,因为在这种情况下wordSearch是"T:\",并且该程序抛出这样的异常:

The error in parsing "T:\" - illegal \ at end of pattern.
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ser*_*kiy 6

你应该逃避\模式.使用"T:\\\\"逐字字符串文字(逐字字符串的优点是不处理转义序列,这使得它易于编写):

var wordSearch = @"T:\\";
var wordReplace = @"T:\Gestion\";

content = Regex.Replace(content, wordSearch, wordReplace);
Run Code Online (Sandbox Code Playgroud)

  • 我认为如果你为他解释`@`也很有用;) (6认同)