简体   繁体   中英

Regex: the “replace” pattern

I have a string which I want to manipulate. Problem is that the replacement contains also regular expressions.

var result = Regex.Replace("Abc", "\r\nAbc\r\n", "\r\n"); 
// or something like that, it can be also \t and so on...

But the result is not a newline, but the string "\\r\\n".

PS: By the way, if I want to replace something by nothing, as very simple example:

Regex.Replace("abc", "abc", "")

regex seems to fail. Cannot strings are replaced by an empty string?

您可以按照以下方式使用正则表达式。

string result = "abc".Replace("abc", string.empty);

尝试这个:

var result = Regex.Replace("Abc", "\r\nAbc\r\n", System.Environment.NewLine);

Try adding the string literal @ identifier before your regex.

var result = Regex.Replace("Abc", @"\r\nAbc\r\n", "\r\n"); 

My guess it that they are being read in as escape characters before they get to the regex engine.

Basically, the pattern getting passed in is this:

"
Abc
"

Intead of this:

"\r\nAbc\r\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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