xarzu
xarzu

Reputation: 9499

How would I use regular expressions to remove a parenthesised substring?

I have a regular expression (regex) question...

How would I use regular expressions to remove the contents in parenthesis in a string in C# like this:

"SOMETHING (#2)"

The part of the string I want to remove always appears within paranthesis and they are always # followed by some number. The rest of the string needs to be left alone.

Upvotes: 1

Views: 190

Answers (1)

amit_g
amit_g

Reputation: 31270

Remove everything including the parenthesis

var input = "SOMETHING (#2) ELSE";
var pattern = @"\(#\d+\)";
var replacement = "";

var replacedString = System.Text.RegularExpressions.Regex.Replace(input, pattern, replacement);

Remove only contents within parenthesis

var input = "SOMETHING (#2) ELSE";
var pattern = @"(.+?)\(#\d+\)(.+?)";
var replacement = "$1()$2";

var replacedString = System.Text.RegularExpressions.Regex.Replace(input, pattern, replacement);

Upvotes: 3

Related Questions