Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove brackets with regular expression in C#

I want to remove square brackets from an SQL string, but only where there is no whitespace inside them.

E.g. "SELECT [intId], [The Description]" should return "SELECT intId, [The Description]".

I can get the square brackets without spaces inside with the regular expression:

\[[^\s]*\]

How can the square brackets from these matches be removed in the original string?

like image 337
Paul Avatar asked Jan 24 '23 20:01

Paul


2 Answers

sql = Regex.Replace(sql, "\\[([^\\s]*)\\]", "$1");
like image 141
Sean Bright Avatar answered Jan 26 '23 11:01

Sean Bright


Regex isn't enough, except only in a one-time way on your above particular string. If you are doing this in an automated fashion over many SQL lines, you can get into a heap of trouble removing brackets you need.

In that case, you need more of an SQL lexer/parser that can help you focus down on columns names only and excludes table names, strings, parameters in triggers or functions, etc...

like image 24
alphadogg Avatar answered Jan 26 '23 09:01

alphadogg