代码之家  ›  专栏  ›  技术社区  ›  roydukkey

将单行注释转换为块注释

  •  6
  • roydukkey  · 技术社区  · 16 年前

    (//...) (/*...*/) . 我在下面的代码中几乎完成了这一点;但是,我需要函数跳过块注释中已经存在的任何单行注释。当前,它匹配任何单行注释,即使单行注释位于块注释中。

     ## Convert Single Line Comment to Block Comments
     function singleLineComments( &$output ) {
      $output = preg_replace_callback('#//(.*)#m',
       create_function(
         '$match',
         'return "/* " . trim(mb_substr($match[1], 0)) . " */";'
       ), $output
      );
     }
    
    2 回复  |  直到 11 年前
        1
  •  3
  •   Brad Gilbert    16 年前

    如前所述,” //... “可以出现在块注释和字符串文本中。因此,如果您在一些正则表达式技巧的帮助下创建一个小的“解析器”,您可以首先匹配这些东西(字符串文本或块注释),然后测试 //... “他在场。

    $code ='A
    B
    // okay!
    /*
    C
    D
    // ignore me E F G
    H
    */
    I
    // yes!
    K
    L = "foo // bar // string";
    done // one more!';
    
    $regex = '@
      ("(?:\\.|[^\r\n\\"])*+")  # group 1: matches double quoted string literals
      |
      (/\*[\s\S]*?\*/)          # group 2: matches multi-line comment blocks
      |
      (//[^\r\n]*+)             # group 3: matches single line comments
    @x';
    
    preg_match_all($regex, $code, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    
    foreach($matches as $m) {
      if(isset($m[3])) {
        echo "replace the string '{$m[3][0]}' starting at offset: {$m[3][1]}\n";
      }
    }
    

    将生成以下输出:

    replace the string '// okay!' starting at offset: 6
    replace the string '// yes!' starting at offset: 56
    replace the string '// one more!' starting at offset: 102
    

    当然,在PHP中可能有更多的字符串文本,但我想你明白我的意思了。

        2
  •  1
  •   Lance Rushing    16 年前

    你可以试着从后面看一看: http://www.regular-expressions.info/lookaround.html

    ## Convert Single Line Comment to Block Comments
    function sinlgeLineComments( &$output ) {
      $output = preg_replace_callback('#^((?:(?!/\*).)*?)//(.*)#m',
      create_function(
        '$match',
        'return "/* " . trim(mb_substr($match[1], 0)) . " */";'
      ), $output
     );
    }
    

    但是,我担心其中可能包含//的字符串。比如:

    如果您的源文件是PHP,则可以使用标记器以更高的精度解析该文件。

    http://php.net/manual/en/tokenizer.examples.php

    编辑: 忘记了固定长度,这可以通过嵌套表达式来克服。上述措施现在应该奏效了。我用以下方法进行了测试:

    $foo = "// this is foo";
    sinlgeLineComments($foo);
    echo $foo . "\n";
    
    $foo2 = "/* something // this is foo2 */";
    sinlgeLineComments($foo2);
    echo $foo2 . "\n";
    
    $foo3 = "the quick brown fox";
    sinlgeLineComments($foo3);
    echo $foo3. "\n";;