2016-03-03 100 views
-1

我想忽略/定位行的非塊註釋段。在單行上解析塊註釋

例如,以下字符串需要將所有結果在一個字符串"foobar"

"foo/*comment*/bar" 
"comm*/foobar/*ent" 
"comment*/foobar" 
"foobar/*comment" 

什麼是實現這一目標的最佳方式是什麼?

+1

見http://stackoverflow.com/questions/35735741/how-can-i-ignore-comments-statements-when-i-reading-java-file/35735793#35735793 – Maljam

+0

那解決方案似乎相當複雜我正試圖想出最簡單的解決方案。 – Ogen

+0

這個問題過於寬泛。這是一個有明確目標的簡單問題。 – Ogen

回答

1

編輯請試試這個:

public static void main(String[] args) { 

    String[] input = new String[]{"foo/*comment*/bar", "comm*/foobar/*ent", "comment*/foobar", "foobar/*comment"}; 
    String pattern = "(?:/\\*[^\\*]+(?:\\*/)?|(?:/\\*)?[^\\*]+\\*/)"; 

    List<String> listMatches = new ArrayList<String>(); 
    String result = ""; 
    for (String m : input) { 
     result = m.replaceAll(pattern, ""); //remove matches 
     listMatches.add(result); // append to list 
     System.out.println(result); 
    } 
} 

輸出:

foobar 
foobar 
foobar 
foobar 

這裏是正則表達式的解釋:

(?:   1st non-capturing group starts 
/\\*  match /* literally 
[^\\*]+  1 or more times characters except * 
(?:   2nd non-capturing group starts 
\\*/  match */ literally  
)   2nd non-capturing group ends 
?   match previous non-capturing group 0 or 1 time 
|   Or (signals next alternative) 
(?:   3rd non-capturing group starts 
/\\*  match /* literally 
)   3rd non-capturing group ends 
?   match previous non-capturing group 0 or 1 time 
[^\\*]+  1 or more times characters except * 
\\*/  match */ one time 
)   1st non-capturing group ends  
+0

我想要的東西不在評論中。 – Ogen

+0

@Ogen:由於正則表達式正在查找所有評論,我們只需要刪除所有匹配。 – Quinn

+0

這實際上運作良好。你能解釋一下正則表達式的不同部分在做什麼嗎? – Ogen

0

這具有相同的邏輯後在this stackoverflow post中,但以遞歸形式實現以取悅您的爲了簡單的願望:

public static String cleanComment(String str) { 
    int open = str.indexOf("/*"), close = str.indexOf("*/"); 

    if((open&close) < 0) return str; 

    open &= Integer.MAX_VALUE; 
    close &= Integer.MAX_VALUE; 

    if(open < close) { 
     if(close > str.length()) { 
      return str.substring(0, open); 
     } else { 
      return str.substring(0, open) + cleanComment(str.substring(close+2)); 
     } 
    } else { 
     return cleanComment(str.substring(close+2)); 
    }  
}