Replace (parsing “\\” illegal at end of pattern) [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:16:02

问题:

This question already has an answer here:

Well I have a mini program with C#, so I do this in my program

wordSearch = "T:\\" wordReplace = "T:\\Gestion\\" content = Regex.Replace(content, wordSearch, wordReplace); 

But doesn't work. The error ir parsing "T:\" - illegal \ at end of pattern.

Any idea ?

Thanks!

Sorry! Perhaps I don't explain well. So... I try again

Hi,

I did a form taking a string for input, but if this string is "T:\", the program take "T:\". So, this string I save in a variable "workShearch".

After this variable uses in:

content = Regex.Replace(content, Regex.Escape(wordSearch), Regex.Escape(wordReplace)); 

But this line contain an error, because wordSearch in this case is "T:\", and the program trhow me an exception like that:

The error ir parsing "T:\" - illegal \ at end of pattern.

Thanks!

回答1:

You should escape \ in pattern. Either use "T:\\\\" or verbatim string literal ( advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write):

var wordSearch = @"T:\\"; var wordReplace = @"T:\Gestion\";  content = Regex.Replace(content, wordSearch, wordReplace); 


回答2:

Escape your '\' again.

wordSearch = "T:\\\\" 

A more elegant solution would be to use the @ modifier infront of your strings

wordSearch = @"T:\\" 


回答3:

\ is escape character, if you want to have \\, you should type \\\\ or place @ in front of your string, which will consider whole string is a plain text

wordSearch = @"T:\\" wordReplace = @"T:\\Gestion\\"  // or   wordSearch = "T:\\\\" wordReplace = "T:\\\\Gestion\\\\" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!