在单行上解析块注释

时间:2016-03-03 04:02:55

标签: java regex string comments

我想忽略/定位一行的非块注释段。

例如,以下字符串需要ALL得到字符串"foobar"

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

实施此方法的最佳方法是什么?

2 个答案:

答案 0 :(得分: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    

答案 1 :(得分: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) );
    }       
}