C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: Value1 is the input that the user specifies. The user in this example specified the string "\123".
Then: This value is then escaped with Regex.Escape and becomes "\\123". So another backslash was added with Escape.
Finally: The Regex.Replace method is called with the escaped value and replaces the pattern "\\123".
C# program that uses Regex.Escape
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// User specified to remove this string.
string value1 = @"\123";
// Escape the input.
value1 = Regex.Escape(value1);
// Write the escaped input.
Console.WriteLine(value1);
// The string we are changing.
string input1 = @"This is\123a string";
// Remove the user-specified pattern.
string output1 = Regex.Replace(input1, value1, "");
// Write the output.
Console.WriteLine(output1);
}
}
Output
(The backslash character was replaced.)
\\123
This isa string
Then: The Replace method can match the character group "\123" and remove it from the final result.
Unescape: The Unescape method transforms the escaped backslash into a regular backslash "\".
String LiteralThen: The method transforms the escaped newline sequence (the two characters "\n") into a real newline.
C# program that unescapes strings
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// You were using a Regex that matches the literal \n.
// With Unescape, you can see the exact text that would be matched.
string result = Regex.Unescape(@"\\n");
Console.WriteLine(result);
// Unescape again to get an actual newline.
result = Regex.Unescape(result);
Console.WriteLine(result == "\n");
}
}
Output
\n
True
Tip: If your program retrieves external input, you can use Escape to eliminate the chance that characters will be incorrectly used.
And: You could use Regex.Unescape to visualize the original representation of the characters, not the escaped representation.