I'm trying to create a search and replace string like this:
src=\"/path/file.jpg\"
into
src=\"http://mysite.com/path/file.jpg\"
By searching for the property src and the equals slash quote. The problem is creating the search string, every time I do it, it becomes a search for
src=\\"/
instead of src=\"/
if property = "src" in this segment, how can I get it to work?string equalsSlashQuote = "=" + @"\" + "\"";
string search = property + equalsSlashQuote + "/";
string replace = property + equalsSlashQuote + SiteURL + "/";
input = input.Replace(search, replace);
The problem is the \, I even tried adding it as the char code value 92 and it still becomes \\ in the search variable.
If you put an @ before the string, the string becames "literal" without using control characters or escapes (with the backslahses).
So @"hello\nico"
will result in a string with the words "hello" and "nico" separated by a slash and not the words "hello" and "ico" separated by a line feed.
You can also define a string without the @ and with control characters like this: "hello\\nico"
which will have the same result. The first backslash is a control character, not an actual value inside the string.
Be aware: if your IDE / debugger shows a value of a string, at will also use the second format to display the text. So the backslash inside the string will be escaped by putting another backslash before it. It looks like the string contains double slashes, but it does not. You can verify this by:
- Checking the length of the string and count the characters.
- Write the value to an output like
Debug.WriteLine
orConsole.WriteLine
which will show that string as it is, without the slashes as escapes.
You say: Every time I do it, it becomes a search for src=\\"/
instead of src=\"/
. Are you sure? I think you are fooled by the IDE / debugger which will show the string with an second backslash, which is just a control character.
来源:https://stackoverflow.com/questions/16196987/c-sharp-how-to-replace-slash-quote