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

前端 未结 7 976
悲哀的现实
悲哀的现实 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:32

    In PHP, i'm using this code to uncomment SQL (only single line):

    $sqlComments = '@(([\'"`]).*?[^\\\]\2)|((?:\#|--).*?$)\s*|(?<=;)\s+@ms';
    /* Commented version
    $sqlComments = '@
        (([\'"`]).*?[^\\\]\2) # $1 : Skip single & double quoted + backticked expressions
        |((?:\#|--).*?$)      # $3 : Match single line comments
        \s*                   # Trim after comments
        |(?<=;)\s+            # Trim after semi-colon
        @msx';
    */
    $uncommentedSQL = trim( preg_replace( $sqlComments, '$1', $sql ) );
    preg_match_all( $sqlComments, $sql, $comments );
    $extractedComments = array_filter( $comments[ 3 ] );
    var_dump( $uncommentedSQL, $extractedComments );
    

    To remove all comments see Regex to match MySQL comments

提交回复
热议问题