2013-03-22 50 views
1

我有一個Java程序,它讀取文本文件並添加並刪除部分內容。它也可以在文本文件中使用內聯和多行註釋。如何使用java跳過帶多個註釋結束標記的多行註釋

例如以下部分將盡快跳過

// inline comment 

/*multiple 
*comment 
*/ 

我有其中多個註釋封閉發生的情況下的問題,例如

/** 
*This 
* is 
*/ 
* a multiple line comment 
*/ 

在這種情況下作爲第一發生註釋結束標記時,將停止註釋的跳過,並將該行的其餘部分打印在輸出文件中。

這裏是我的怎麼做這個

boolean commentStart = false; 
boolean commentEnd = false; 

if(line.trim().indexOf("/*") != -1) { // start 
    commentStart = true; 
} 

if(line.trim().indexOf("*/") != -1 && commentStart) { // closed 
    commentEnd = true; 
    commentStart = false; 
} 

if(commentStart || (!commentStart && commentClosed)) { 
    //skip line 
} 

任何幫助嗎?謝謝。

+0

我認爲你的意思是嵌套評論,但你的例子沒有證明這種情況。 – 2013-03-22 10:50:42

+0

@MarkoTopolnik:是嵌套評論也可以是一個案例。 – 2013-03-22 10:51:44

+1

根據您首先展示的內容,您可以繼續檢查文本,直到找到下一個\ * /,存儲它的位置,檢查第一個/ *的索引和最後一個索引/ *之間是否存在/ *您將在兩個位置之間跳過文本。 – Anila 2013-03-22 10:54:17

回答

0

除非將自己限制爲嵌套註釋,否則您的文件格式不正確。如果沒關係,那麼你需要定義什麼的評論,如果不只是/**/之間的東西。在你的例子中,它看起來像你的評論的定義是以*/,/**開頭的任何行。在正則表達式:^[/\\\b]?*

如果這樣,我只是跳過行,如果他們匹配的正則表達式。

+0

據我說,任何以/ *開頭並以* /結尾的行以及這兩者之間的任何內容都應該是一條評論。 – 2013-03-22 11:03:11

+0

好吧,我明白了。那麼你必須提前讀一行。檢查@Anila的答案。 – Miquel 2013-03-22 11:05:57

0

我有一個Perl正則表達式,它會從Java中刪除註釋,並充分考慮引用的字符串和所有內容。它唯一不喜歡的是使用\ uXXXX序列創建的評論或引用。

sub strip_java_comments_and_quotes 
{ 
    s!( (?: \" [^\"\\]* (?: \\. [^\"\\]*)* \") 
    | (?: \' [^\'\\]* (?: \\. [^\'\\]*)* \') 
    | (?: \/\/ [^\n] *) 
    | (?: \/\* .*? \*\/) 
    ) 
    ! 
    my $x = $1; 
    my $first = substr($x, 0, 1); 
    if ($first eq '/') 
    { 
     # Replace comment with equal number of newlines to keep line count consistent 
     "\n" x ($x =~ tr/\n//); 
    } 
    else 
    { 
     # Replace quoted string with equal number of newlines to keep line count consistent 
     $first . ("\n" x ($x =~ tr/\n//)) . $first; 
    } 
    !esxg; 
} 

我會在將其轉換成Java一展身手:

Pattern re = Pattern.compile(
"( (?: \" [^\"\\\\]* (?: \\\\. [^\"\\\\]*)* \")" + 
"| (?: ' [^'\\\\]* (?: \\\\. [^'\\\\]*)* ')" + 
"| (?: // [^\\n] *)" + 
"| (?: /\\* .*? \\*/)" + 
")", Pattern.DOTALL | Pattern.COMMENTS); 
Matcher m = Pattern.matcher(entireSourceFile); 
Stringbuffer replacement = new Stringbuffer(); 
while (m.find()) 
{ 
     String match = m.group(1); 
     String first = match.substring(0, 1); 
     m.appendReplacement(replacement, ""); // Beware of $n in replacement string!! 
     if (first.equals("/")) 
     { 
     // Replace comment with equal number of newlines to keep line count consistent 
     replacement.append(match.replaceAll("[^\\n]", "")); 
     } 
     else 
     { 
     // Replace quoted string with equal number of newlines to keep line count consistent 
     // Although Java quoted strings aren't legally allowed newlines in them 
     replacement.append(first).append(match.replaceAll("[^\\n]", "")).append(first); 
     } 
} 
m.appendTail(replacement); 

類似的東西!