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

前端之家收集整理的这篇文章主要介绍了正则表达式从SQL语句中删除注释前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用正则表达式从sql语句中删除注释.

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

  1. (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|'(?:[^']|'')*'|(--.*)

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

例如,如果我有

  1. SELECT ' -- Hello -- ' FROM DUAL

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

这是在ASP / VBscript中.

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

PHP中,我使用此代码取消注释sql
  1. $sqlComments = '@(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
  2. /* Commented version
  3. $sqlComments = '@
  4. (([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
  5. |( # $3 : Match comments
  6. (?:\#|--).*?$ # - Single line comments
  7. | # - Multi line (nested) comments
  8. /\* # . comment open marker
  9. (?: [^/*] # . non comment-marker characters
  10. |/(?!\*) # . ! not a comment open
  11. |\*(?!/) # . ! not a comment close
  12. |(?R) # . recursive case
  13. )* # . repeat eventually
  14. \*\/ # . comment close marker
  15. )\s* # Trim after comments
  16. |(?<=;)\s+ # Trim after semi-colon
  17. @msx';
  18. */
  19. $uncommentedsql = trim( preg_replace( $sqlComments,'$1',$sql ) );
  20. preg_match_all( $sqlComments,$sql,$comments );
  21. $extractedComments = array_filter( $comments[ 3 ] );
  22. var_dump( $uncommentedsql,$extractedComments );

猜你在找的正则表达式相关文章