Java 需要正则表达式在php中格式化文件
我有一个java文件,我想在网上发布。我正在使用php格式化文件 有人知道用正则表达式把评论变成蓝色吗 输入:Java 需要正则表达式在php中格式化文件,java,php,regex,Java,Php,Regex,我有一个java文件,我想在网上发布。我正在使用php格式化文件 有人知道用正则表达式把评论变成蓝色吗 输入: /***** *This is the part *I want to turn blue *for my class *******************/ class MyClass{ String s; } 谢谢。Naive版本: $formatted = preg_replace('|(/\*.*?\*/)|m', '<span class="blue">
/*****
*This is the part
*I want to turn blue
*for my class
*******************/
class MyClass{
String s;
}
谢谢。Naive版本:
$formatted = preg_replace('|(/\*.*?\*/)|m', '<span class="blue">$1</span>', $java_code_here);
$formatted=preg\u replace(“|”(/\*.*?\*/)| m'、“$1'、$java\u code\u在此);
。。。未经测试、YMMV等。一般来说,您将无法仅使用正则表达式解析Java文件的特定部分-Java不是一个。如果文件具有其他结构(例如“它总是以注释开头,后跟换行符,后跟类定义”),则可以为这种情况生成正则表达式。例如,您将匹配
/\*+(.*?)\*+/$
,其中假定
匹配多行,$
匹配一行的结尾
一般来说,要使正则表达式起作用,首先定义要查找的模式(严格地说,但使用口语),然后将其转换为标准正则表达式表示法
祝你好运。能够解析简单引号的正则表达式应该能够找到C/C++风格语言中的注释。
我假设Java就是这种类型 这是其他人提供的Perl常见问题解答示例,不过我添加了关于//样式注释(带或不带换行符)的部分,并对其进行了重新格式化 它基本上进行全局搜索和替换。如果不是注释,则会逐字替换数据,否则会使用颜色格式标记替换注释 您应该能够将其应用于php,并且为了清晰起见对其进行了扩展(尽管可能过于清晰)
s{
##意见,第1组:
(
/\*##开始/*…*/评论
[^*]*\*+#非-*后跟1个或多个*
(?:
[^/*][^*]*\*+
)*###0-或更多不以/
##但一定要以“*”结尾
/##结束/*…*/评论
|
//##开始//…评论
(?:
[^\\\]##任何非连续字符^\
|##或
\\\n?##任何后跟0-1换行符的连续字符\n
)*?##完成0次-多次,在评论的第一个结尾处停止
\n##结束//评论
)
|####或者,各种非评论的内容,第2组:
(
“(?:\.\.[^”\\])*”双引号文本
|
“(?:\.\.[^'\]])*”#单引号文本
|
.##还有其他字符吗
[^/“'\]*##字符,它不会开始注释、字符串和转义
)##或继续(转义+换行)
}
{定义为$2?$2:“$1”}gxse;
您可以使用或这样的解决方案吗?你不必重新发明轮子
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;