Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing text in all kinds of braces

Tags:

string

c#

I have a string "hello [world] this {is} a (test)" I want to remove all text in braces, e.g. returning "hello this a". But only if the braces match.
Anyone have a nice neat solution?

like image 455
Andrew White Avatar asked May 16 '10 18:05

Andrew White


1 Answers

You can use a regular expression:

s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);

The \s*? matches any white space before the brackets.
The (?: ) is a non-matching parenthesis to group the conditions inside it.
The \(.*?\) is mathing parentheses with zero or more characters between them.

like image 95
Guffa Avatar answered Oct 03 '22 04:10

Guffa