简体   繁体   中英

How to remove comments from a given String in Java?

how do I remove comments start with "//" and with /**, * etc.? I haven't found any solutions on Stack Overflow that has helped me very much, a lot of them have been way above my head and I'm still at most basics.

What I have thought about so far:

for (int i = 0; i < length; i++) {
  for (j = i; j < length; j++) {
        if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '/')

But I'm not really sure how to replace the words following those characters. And how to end when to stop the replacement with a "//" comment. With the /* comments, atleast conceptually I know I should replace all words till "*/" pops up. Though again, I'm not sure how to limit the replacement till that point. To replace I thought replacing the charAt after the second "/" with an empty string until....where? I cannot figure out where to "end" the replacing.

I have looked at a few implementations on Stack, but I really didn't get it. Any help is appreciated, especially if it's at a basic level and understandable for someone not well versed in programming!

Thanks.

I have done something similar with regex (Java 9+) :

// Checks for
// 1) Single char literal '"'
// 2) Single char literal '\"'
// 3) Strings; termination ignores \", \\\", ..., but allows ", \\", \\\\", ...
// 4) Single-line comment // ... to first \n
// 5) Multi-line comments /*[*] ... */
Pattern regex = Pattern.compile(
    "(?s)('\"'|'\\\"'|\".*?(?<!\\\\)(?:\\\\\\\\)*\"|//[^\n]*|/\\*.*?\\*/)");

// Assuming 'text' contains your java text
// Leaves 1,2,3) unchanged and replaces comments 4,5) with ""
// Need quoteReplacement to prevent matcher processing $ and \
String textWithoutComments = regex.matcher(text).replaceAll(
    m -> m.group().charAt(0) == '/' ? "" : Matcher.quoteReplacement(m.group()));

If you don't have Java 9+ then you could use this replace function:

String textWithoutComments = replaceAll(regex, text,
    m -> m.group().charAt(0) == '/' ? "" : m.group());
public static String replaceAll(Pattern p, String s,
    Function<MatchResult, String> replacer) {
    Matcher m = p.matcher(s);
    StringBuilder b = new StringBuilder();
    int lastStart = 0;
    while (m.find()) {
        String replacement = replacer.apply(m);
        b.append(s.substring(lastStart, m.start())).append(replacement);
        lastStart = m.end();
    }
    return b.append(s.substring(lastStart)).toString();
}

I'm not sure if you're using an IDE like IntelliJ or Eclipse but you could do this without using code if you're just interested in removing all comments for the project. You can do this with "Replace in Path" tool. Notice how "Regex" is checked, allowing us to match lines based on regular expressions.

在此处输入图像描述

This configuration in the tool will delete all lines starting with a // and replace it with an empty line.

The command to get to this on a Mac is ctrl + shift + r .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM