-1

I would like to ignore/target the non-block-commented segments of a line.

For example, the following strings need to ALL result in a string "foobar"

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

What is the best way to implement this?

Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 1
    See http://stackoverflow.com/questions/35735741/how-can-i-ignore-comments-statements-when-i-reading-java-file/35735793#35735793 – Maljam Mar 03 '16 at 04:03
  • That solution seems rather complex. I am trying to come up with the simplest solution. – Ogen Mar 03 '16 at 04:07
  • How is this question too broad. This is a simple question that has a clear objective. – Ogen Mar 03 '16 at 11:36

2 Answers2

1

EDIT Please try this:

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);
    }
}

Output:

foobar
foobar
foobar
foobar

Here is the explanation of the regex:

(?:         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    
Quinn
  • 4,394
  • 2
  • 21
  • 19
0

This has the same logic as the post in this stackoverflow post, but implemented in a recursive form to please your desire for simplicity:

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) );
    }       
}
Community
  • 1
  • 1
Maljam
  • 6,244
  • 3
  • 17
  • 30