需要正则表达式来格式化PHP中的文件

时间:2011-08-08 14:58:39

标签: java php regex

我有一个我想在线发布的java文件。我使用php来格式化文件。

是否有人知道正则表达式将评论变为蓝色?

INPUT:

/*****
*This is the part 
*I want to turn blue
*for my class
*******************/
class MyClass{
  String s;

}

感谢。

3 个答案:

答案 0 :(得分:1)

Naiive版本:

$formatted = preg_replace('|(/\*.*?\*/)|m', '<span class="blue">$1</span>', $java_code_here);

......没有经过测试,YMMV等...

答案 1 :(得分:0)

通常,您将无法仅使用正则表达式解析Java文件的特定部分 - Java不是regular language。如果您的文件具有其他结构(例如“它始终以注释后跟换行符开头,后跟类定义”),则可以为此类情况生成正则表达式。例如,您匹配/\*+(.*?)\*+/$,其中假设.匹配多行,而$匹配一行的结尾。

通常,要使正则表达式工作,首先要定义要查找的模式(严格地,但是使用口语),然后将其转换为标准正则表达式表示法。

祝你好运。

答案 2 :(得分:0)

可以解析简单引号的正则表达式应该能够在C / C ++风格的语言中找到注释 我假设Java属于那种类型。

这是其他人的Perl常见问题样本,虽然我添加了关于//样式注释的部分(有或没有续行)并重新格式化。

它基本上进行全局搜索和替换。如果不是评论,则逐字替换数据,否则用您的颜色格式标签替换评论。

你应该能够将它改编为php,并且为了清晰起见而进行了扩展(尽管可能过于清晰)。

s{
   ## Comments, group 1:
    (
        /\*         ##  Start of /* ... */ comment
        [^*]*\*+    ##  Non-* followed by 1-or-more *'s
        (?:
            [^/*][^*]*\*+
        )*          ##  0-or-more things which don't start with /
                    ##    but do end with '*'
        /           ##  End of /* ... */ comment

      |  
        //          ## Start of // ... comment
        (?:
            [^\\]         ## Any Non-Continuation character ^\
          |               ##   OR
            \\\n?         ## Any Continuation character followed by 0-1 newline \n

         )*?            ## To be done 0-many times, stopping at the first end of comment

         \n         ##  End of // comment
    )

 | ##  OR,  various things which aren't comments, group 2:
    (
        " (?: \\. | [^"\\] )* "  ## Double quoted text
      |

        ' (?: \\. | [^'\\] )* '  ## Single quoted text
      |
        .           ##  Any other char
        [^/"'\\]*   ##  Chars which doesn't start a comment, string, escape
    )               ##    or continuation (escape + newline)
 }
 {defined $2 ? $2 : "<some color>$1</some color>"}gxse;