加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式从SQL语句中删除注释

发布时间:2020-12-14 06:32:24 所属栏目:百科 来源:网络整理
导读:我正在尝试使用正则表达式从SQL语句中删除注释. 这个正则表达式几乎有效: (/*([^*]|[rn]|(*+([^*/]|[rn])))**+/)|'(?:[^']|'')*'|(--.*) 除了最后一部分不能很好地处理“ – ”评论.问题是处理SQL字符串,用”分隔. 例如,如果我有 SELECT ' -- Hello
我正在尝试使用正则表达式从SQL语句中删除注释.

这个正则表达式几乎有效:

(/*([^*]|[rn]|(*+([^*/]|[rn])))**+/)|'(?:[^']|'')*'|(--.*)

除了最后一部分不能很好地处理“ – ”评论.问题是处理SQL字符串,用”分隔.

例如,如果我有

SELECT ' -- Hello -- ' FROM DUAL

它不应该匹配,但它匹配.

这是在ASP / VBscript中.

我想过从右到左匹配,但我不认为VBScript的正则表达式引擎支持它.也试图摆弄负面的背后,但结果并不好.

在PHP中,我使用此代码取消注释SQL:
$sqlComments = '@((['"]).*?[^]2)|((?:#|--).*?$|/*(?:[^/*]|/(?!*)|*(?!/)|(?R))**/)s*|(?<=;)s+@ms';
/* Commented version
$sqlComments = '@
    ((['"]).*?[^]2) # $1 : Skip single & double quoted expressions
    |(                   # $3 : Match comments
        (?:#|--).*?$   # - Single line comments
        |                # - Multi line (nested) comments
         /*             #   . comment open marker
            (?: [^/*]    #   . non comment-marker characters
                |/(?!*) #   . ! not a comment open
                |*(?!/) #   . ! not a comment close
                |(?R)    #   . recursive case
            )*           #   . repeat eventually
        */             #   . comment close marker
    )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 );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读