【问题标题】:Regex to match MySQL comments正则表达式匹配 MySQL 注释
【发布时间】:2011-10-29 07:57:36
【问题描述】:

我需要从 MySQL 查询中查找并删除所有 cmets。我遇到的问题是避免使用引号或反引号内的注释标记(--、#、/* ... */)。

【问题讨论】:

  • 查找很容易。对删除进行手动编辑。其他任何内容都可能会破坏您的查询字符串。
  • regex 的语法略有不同,具体取决于您使用它的用途。您在 javascript、php、asp 中执行此操作?
  • 你能举个例子吗?

标签: mysql regex comments


【解决方案1】:

此代码适用于我:

function strip_sqlcomment ($string = '') {
    $RXSQLComments = '@('(''|[^'])*')|(--[^\r\n]*)|(\#[^\r\n]*)|(/\*[\w\W]*?(?=\*/)\*/)@ms';
    return (($string == '') ?  '' : preg_replace( $RXSQLComments, '', $string ));
}

只要稍微调整一下正则表达式,它就可以用来剥离任何语言的 cmets

【讨论】:

    【解决方案2】:

    不幸的是,您只能使用正则表达式进行非常有限的 SQL 格式化。主要原因是有例如您不想删除的 cmets 或不能小写/大写的标记,因为它们是文字的一部分,并且由于不同的 SQL 方言使用不同的封闭字符,有时甚至使用不同的 SQL 方言,因此并不总是容易找到文字的开头和结尾几个字符来包围文字。有时人们会将 SQL 片段放在注释中以供以后重用。您不想重新格式化这些 SQL。 当您使用正则表达式更改 SQL 语句时,在您的 DB 工具中再次运行更改后的 SQL,以确保您没有对逻辑进行任何更改。我听说有人在不检查结果的情况下对数百个 SQL 文件运行正则表达式。我认为这是非常危险的一步。永远不要更改正在运行的 SQL ;-)

    【讨论】:

      【解决方案3】:

      在 PHP 中,我使用此代码取消注释 SQL:

      $sqlComments = '@(([\'"`]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
      /* Commented version
      $sqlComments = '@
          (([\'"`]).*?[^\\\]\2) # $1 : Skip single & double quoted + backticked 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 );
      

      【讨论】:

        【解决方案4】:

        不幸的是,您要执行的操作需要上下文无关的语法,而不能使用正则表达式来完成。这是因为嵌套,在计算机科学理论中,我们需要一个堆栈来跟踪您何时嵌套在引号或其他内容中。 (从技术上讲,这需要下推自动机而不是常规语言。等等等等学术界等等......)这并不难实现,但必须通过程序来完成,老实说,它可能需要比你想要的更多的努力花费。

        如果你不介意剪切和粘贴,可以使用SQLInform。在线模式免费,支持评论删除。

        更新

        考虑到我在下面收到的评论,我使用了 MySQL 编辑器。我错了——他们实际上禁止嵌套任何比一层更深的东西。您不能再在评论中嵌套评论(如果可以的话)。无论如何,我将只为 SQLInform 链接留下我的答案。

        【讨论】:

        • 考虑:' /* hello world */ '' --i; '。这些 cmets(或第二种情况下的一元运算符)嵌套在引号内,很可能不是用户想要剥离的东西。
        【解决方案5】:

        有人为你写的。转换为您需要的任何语言。

        Use Regular Expressions to Clean SQL Statements

        这是答案中包含的 C# 翻译,以防原始链接消失。我还没有测试过,但它看起来不错。

        public static string ToRaw(string commandText)
        {
            RegexOptions regExOptions = (RegexOptions.IgnoreCase | RegexOptions.Multiline);
            string rawText=commandText;
            string regExText = @”(‘(”|[^'])*’)|([\r|\n][\s| ]*[\r|\n])|(–[^\r\n]*)|(/\*[\w\W]*?(?=\*/)\*/)”;
            //string regExText = @”(‘(”|[^'])*’)|[\t\r\n]|(–[^\r\n]*)|(/\*[\w\W]*?(?=\*/)\*/)”;
            //’Replace Tab, Carriage Return, Line Feed, Single-row Comments and
            //’Multi-row Comments with a space when not included inside a text block.
        
            MatchCollection patternMatchList = Regex.Matches(rawText, regExText, regExOptions);
            int iSkipLength = 0;
            for (int patternIndex = 0; patternIndex < patternMatchList.Count; patternIndex++)
            {
                if (!patternMatchList[patternIndex].Value.StartsWith("'") && !patternMatchList[patternIndex].Value.EndsWith("'"))
                {
                    rawText = rawText.Substring(0, patternMatchList[patternIndex].Index – iSkipLength) + " " + rawText.Substring(patternMatchList[patternIndex].Index – iSkipLength + patternMatchList[patternIndex].Length);
                    iSkipLength += (patternMatchList[patternIndex].Length – " ".Length);
                }
            }
            //'Remove extra spacing that is not contained inside text qualifers.
            patternMatchList = Regex.Matches(rawText, "'([^']|'')*'|[ ]{2,}", regExOptions);
            iSkipLength = 0;
            for (int patternIndex = 0; patternIndex < patternMatchList.Count; patternIndex++)
            {
                if (!patternMatchList[patternIndex].Value.StartsWith("'") && !patternMatchList[patternIndex].Value.EndsWith("'"))
                {
                    rawText = rawText.Substring(0, patternMatchList[patternIndex].Index – iSkipLength)+" " + rawText.Substring(patternMatchList[patternIndex].Index – iSkipLength + patternMatchList[patternIndex].Length);
                    iSkipLength += (patternMatchList[patternIndex].Length – " ".Length);
                }
            }
            //'Return value without leading and trailing spaces.
            return rawText.Trim();
        }
        

        【讨论】:

          猜你喜欢
          • 2012-10-26
          • 2010-11-14
          • 2017-05-22
          • 2015-03-04
          • 2013-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多