开发者

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

开发者 https://www.devze.com 2023-03-19 07:53 出处:网络
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:

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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消