Reputation: 243
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?
Upvotes: 0
Views: 111
Reputation: 4078
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();
Upvotes: 1
Reputation: 5019
string str = @"This is a drill (2).";
string reseult = Regex.Replace(str, "\\((\\d+)\\)", "(<x>$1</x>)");
Console.WriteLine(reseult);
Console.ReadLine();
Upvotes: 1