views:

3211

answers:

2

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?

+3  A: 
sql = Regex.Replace(sql, "\\[([^\\s]*)\\]", "$1");
Sean Bright
You can improve the readability of that expression by using @"\[(\S+)\]"
Juliet
This may have issues with nested brackets. Whether it does or not sort of depends on the syntax rules you're dealing with. [foo[bar baz]] will wind up being replaced by foo[bar baz].
nsayer
+3  A: 

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...

alphadogg