Remove brackets with regular expression in C#
Solution 1
sql = Regex.Replace(sql, "\\[([^\\s]*)\\]", "$1");
Solution 2
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...
Momo
I work as a software development manager, working mostly with C#, Azure and SQL Server.
Updated on June 08, 2022Comments
-
Momo almost 2 years
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?
-
Joel Coehoorn about 15 yearsAre you sure you want to do this? What about brackets in string literals? Or columns names that match reserved words?
-
Momo about 15 yearsAbsolutely, I know there are pitfalls here. I suppose my wider problem was how you can replace regular expression matches with something from the match itself. I understand that now, with the help of this example. This replacement will be done only after the string has undergone some parsing.
-
-
nsayer about 15 yearsThis 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].
-
tymtam over 11 yearsFor
SELECT [intId],[intId2], [The Description], [init[x]]
this returnsSELECT intId],[intId2, [The Description], init[x]
. If you change * (greedy) to *? (not-greedy) the result would beSELECT intId,intId2, [The Description], init[x]
.