Remove brackets with regular expression in C#

13,967

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

Share:
13,967
Momo
Author by

Momo

I work as a software development manager, working mostly with C#, Azure and SQL Server.

Updated on June 08, 2022

Comments

  • Momo
    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
      Joel Coehoorn about 15 years
      Are you sure you want to do this? What about brackets in string literals? Or columns names that match reserved words?
    • Momo
      Momo about 15 years
      Absolutely, 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
    nsayer about 15 years
    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].
  • tymtam
    tymtam over 11 years
    For SELECT [intId],[intId2], [The Description], [init[x]] this returns SELECT intId],[intId2, [The Description], init[x]. If you change * (greedy) to *? (not-greedy) the result would be SELECT intId,intId2, [The Description], init[x].