Regex to remove single-line SQL comments (--)

前端 未结 7 1040
悲哀的现实
悲哀的现实 2021-01-15 08:52

Question:

Can anybody give me a working regex expression (C#/VB.NET) that can remove single line comments from a SQL statement ?

I mean these comments:

7条回答
  •  [愿得一人]
    2021-01-15 09:25

    Using System.Text.RegularExpressions;
    
    public static string RemoveSQLCommentCallback(Match SQLLineMatch)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        bool open = false; //opening of SQL String found
        char prev_ch = ' ';
    
        foreach (char ch in SQLLineMatch.ToString())
        {
            if (ch == '\'')
            {
                open = !open;
            }
            else if ((!open && prev_ch == '-' && ch == '-'))
            {
                break;
            }
            sb.Append(ch);
            prev_ch = ch;
        }
    
        return sb.ToString().Trim('-');
    }
    

    The code

    public static void Main()
    {
        string sqlText = "WHERE DEPT_NAME LIKE '--Test--' AND START_DATE < SYSDATE -- Don't go over today";
        //for every matching line call callback func
        string result = Regex.Replace(sqlText, ".*--.*", RemoveSQLCommentCallback);
    }
    

    Let's replace, find all the lines that match dash dash comment and call your parsing function for every match.

提交回复
热议问题