我正在尝试使用正则表达式从sql语句中删除注释.
这个正则表达式几乎有效:
- (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|'(?:[^']|'')*'|(--.*)
除了最后一部分不能很好地处理“ – ”评论.问题是处理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 );