2012-05-14 27 views
2

我需要在字符串中找到所有多行註釋,並用空格(如果註釋在一行中)或\n(如果註釋位於多行)替換它們。 例如:如何使用正則表達式抑制單行和多行註釋?

int/* one line comment */a; 

應改爲:

int a; 

這:

int/* 
more 
than one 
line comment*/a; 

應改爲:

int 
a; 

我有一個字符串所有的文字和我使用這個命令:

file = file.replaceAll("(/\\*([^*]|(\\*+[^*/]))*\\*+/)"," "); 

其中file是字符串。

問題是它找到了所有多行註釋,我想將它分開爲2個案例。 我該怎麼辦?

回答

0

這可以使用Matcher.appendReplacementMatcher.appendTail來解決。

String file = "hello /* line 1 \n line 2 \n line 3 */" 
      + "there /* line 4 */ world"; 

StringBuffer sb = new StringBuffer(); 
Matcher m = Pattern.compile("(?m)/\\*([^*]|(\\*+[^*/]))*\\*+/").matcher(file); 

while (m.find()) { 

    // Find a comment 
    String toReplace = m.group(); 

    // Figure out what to replace it with 
    String replacement = toReplace.contains("\n") ? "\n" : ""; 

    // Perform the replacement. 
    m.appendReplacement(sb, replacement); 
} 

m.appendTail(sb); 

System.out.println(sb); 

輸出:

hello 
there world 

注:如果你想保持正確的行數/列的所有文本是內部意見(好,如果你想在錯誤消息等中引用回源代碼)我會推薦做

String replacement = toReplace.replaceAll("\\S", " "); 

它用空格替換所有非空格。這樣\n被保留,並

"/* abc */" 

"   " 
取代