我有,我想網上發帖的Java文件。我使用PHP來格式化文件。需要的正則表達式格式的文件在PHP
有誰知道正則表達式變成藍色的意見嗎?
輸入:
/*****
*This is the part
*I want to turn blue
*for my class
*******************/
class MyClass{
String s;
}
感謝。
我有,我想網上發帖的Java文件。我使用PHP來格式化文件。需要的正則表達式格式的文件在PHP
有誰知道正則表達式變成藍色的意見嗎?
輸入:
/*****
*This is the part
*I want to turn blue
*for my class
*******************/
class MyClass{
String s;
}
感謝。
Naiive版本:
$formatted = preg_replace('|(/\*.*?\*/)|m', '<span class="blue">$1</span>', $java_code_here);
...沒有測試,情況因人而異,等等
一般情況下,你將無法解析只使用普通的Java文件的特定部分表達式 - Java不是regular language。如果你的文件有額外的結構(比如「它總是以註釋開頭,後面跟着一個換行符,然後是一個類定義」),你可以爲這種情況生成一個正則表達式。舉例來說,你會匹配/\*+(.*?)\*+/$
,其中.
假設來匹配多個行,$
行的結尾匹配。
一般來說,做一個正則表達式的工作,首先要定義你要查找的模式(嚴格,但在口語中),然後把這一標準的正則表達式符號。
祝你好運。
,可以簡單解析引號中的正則表達式應該能夠找到在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;
你可以使用這樣http://alexgorbatchev.com/SyntaxHighlighter/或http://qbnz.com/highlighter/一個解決方案嗎?你不必重新發明輪子。 =) – Jens