Don_B
Don_B

Reputation: 243

How to replace a regex with parentheses keeping the parentheses c#?

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

Answers (2)

Rishav
Rishav

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

Roy Shmuli
Roy Shmuli

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

Related Questions