I'm trying to do some regex replace on files and the strings that I'm trying to replace contains things like ()[]{}
...etc and I want to keep as it after the replace, here is a simple example
string str = @"This is a drill (2).";
string reseult = Regex.Replace(str, "\\((\\d+)\\)", "\\(<x>$1</x>\\)");
Console.WriteLine(reseult);
Console.ReadLine();
The result should output This is a drill (<x>2</x>).
but it is outputting This is a drill \\(<x>2</x>\\).
Same goes for []
Why is this happening and how to solve this without using the verbatim alternative?
string str = @"This is a drill (2).";
string reseult = Regex.Replace(str, "\\((\\d+)\\)", "(<x>$1</x>)");
Console.WriteLine(reseult);
Console.ReadLine();
string str = @"This is a drill (2).";
string reseult = Regex.Replace(str, "\\((\\d+)\\)", "(<x>$1</x>)");
Console.WriteLine(reseult);
Console.ReadLine();
You don't need to escape parentheses in the final part. It is not regex. Similarly for other braces you dont need to escape them either. Just use this.
string str = @"This is a drill (2).";
string reseult = Regex.Replace(str, "\\((\\d+)\\)", "{<x>$1</x>}");
Console.WriteLine(reseult);
Console.ReadLine();
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.