【问题标题】:How to strip executable comments of MySQL by regexp如何通过正则表达式去除 MySQL 的可执行注释
【发布时间】:2012-02-09 17:06:00
【问题描述】:

我需要在 mysqldump 结果中获取可执行 cmets 的内容,但是对于正则表达式

/\/\*\!\d+\s+(.*?)\*\//s

并像这样输入数据:

/*!50003 text
some text else
/*
comment
also comment
*/
text...
and also text...
*/

我得到错误的结果,因为它只从“文本”到“也注释”行获取数据。我怎样才能跳过评论进入评论? 谢谢。

UPD:我不能使用“^”和“$”来标记输入的开始和结束,因为我在输入中有很多可执行语句。

UPD2:我想要的输出:

text
some text else
/*
comment
also comment
*/
text...
and also text...

并非所有人都在下面的评论中输入如何。我认为这很奇怪,得到与输入相同的输出。

UPD3: 可执行注释的开头必须是 /*!ANYNUMBER。它必须被跳过并且不包含在输出中。可执行注释的结尾很简单 */ 右输出示例在“UPD2”中呈现。

【问题讨论】:

  • 您想“解开”所有 cmets 的最外层评论,剥离评论的某些部分,还是只想对以特定模式开头的 cmets 执行此操作?第一部分的确切模式是什么?究竟是“!50003 text”,还是数字可以是任何东西? “文本”部分的确切模式是什么?是一个字吗?一切直到新线? overall goal 是什么?
  • 当然,我问的是“常见”问题,而不是“!50003”被硬编码的情况。

标签: php regex strip


【解决方案1】:

纯正则表达式无法处理嵌套,但 PHP 的风格可以使用 recursion。使用PCRE_EXTENDED modifier 这样我们就可以有空格和cmets:

%(               # opening RE delimiter, group start
  /\*            # comment open marker
    (  [^/*]     # non comment-marker characters
     | /(?!\*)   # '/' not followed by '*', so not a comment open
     | \*(?!/)   # '*' not followed by '/', so not a comment close
     | (?R)      # recursive case
    )*           # repeat any number of times
  \*/            # comment close marker
)%x              # group end, closing RE delimiter, PCRE_EXTENDED

简而言之:

%(/\*([^/*]|/(?!\*)|\*(?!/)|(?R))*\*/)%x

使用中:

<?php

$commentRE = '%(/\*([^/*]|/(?!\*)|\*(?!/)|(?1))*\*/)%';
$doc = <<<EOS

USE database;

/* comment
and a
/* nested comment /* me too */
   now exiting
 */
the comment */


/*!50003 text
some text else
/*
comment
also comment
*/
text...
and also text...
*/

CREATE TABLE IF NOT EXISTS ...

EOS;

preg_match_all($commentRE, $doc, $parts);
var_export($parts[0]);

结果:

大批 ( 0 => '/* 注释 和一个 /* 嵌套评论 /* 我也是 */ 现在退出 */ 评论 */', 1 => '/*!50003 文本 其他一些文字 /* 评论 也评论 */ 文本... 还有文字... */', )

【讨论】:

    【解决方案2】:

    基于这个出色的解决方案,我做了一个 PHP 正则表达式来删除所有类型的 cmets(并且只有 cmets,而不是看起来像 cmets 的引用文本;): Regex to match MySQL comments

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 2011-02-14
      • 2010-10-13
      • 2011-05-11
      • 2013-06-25
      • 2011-01-28
      • 2011-10-29
      • 2012-04-08
      相关资源
      最近更新 更多