Подтвердить что ты не робот

Удалить все комментарии в файлах Java

У меня есть много комментариев, как показано ниже. Есть простой способ удалить все комментарии?

IDE Eclipse Kepler

/* 34:   */

/*

 * JD-Core Version:    0.7.0.1

 */
4b9b3361

Ответ 1

Я нашел решение Регулярное выражение с поиском нескольких строк.

Вот регулярное выражение, используемое для поиска двух типов комментариев

\/\*([\S\s]+?)\*\/ и (?s)/\*.*?\*/

Откройте файл .java с комментариями и откройте диалоговое окно поиска. (Search -> File Search) и вставьте один из указанных выше регистров и установите флажок Regular expression с правой стороны. Теперь вы можете выполнить поиск и выбрать "Заменить все", чтобы заменить его, ничего не набрав во втором поле.

С помощью опции replace-with я очистил все комментарии от java файлов.

Ответ 2

Я сделал открытую исходную библиотеку для этой цели, вы можете удалить комментарии Java.

Он поддерживает удаление или удаление TODO.

Также он поддерживает JavaScript, HTML, CSS, Свойства, JSP и комментарии XML.

Маленький фрагмент кода, как его использовать:

 public static void main(String[] args) throws CommentRemoverException {

 // root dir is: /Users/user/Projects/MyProject
 // example for startInternalPath

 CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
        .removeJava(true) // Remove Java file Comments....
        .removeJavaScript(true) // Remove JavaScript file Comments....
        .removeJSP(true) // etc.. goes like that
        .removeTodos(false) //  Do Not Touch Todos (leave them alone)
        .removeSingleLines(true) // Remove single line type comments
        .removeMultiLines(true) // Remove multiple type comments
        .startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
        .setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
        .build();

 CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
                  commentProcessor.start();        
  }

Ответ 3

Поскольку никто не упоминал инструменты обработки текста grep, sed, awk и т.д. в * NIX, я размещаю здесь свое решение.

Если ваш os - * NIX, вы можете использовать инструмент обработки текста sed, чтобы удалить комментарии.

sed '/\/\*/{:loop;/\/\*.*\*\//{d;b out};N;b loop};:out' yourfile.java

Ответ 4

Я думаю, что eclipse поддерживает поиск и замену регулярных выражений. Я бы попробовал что-то вроде:

search: (?s)(?>\/\*(?>(?:(?>[^*]+)|\*(?!\/))*)\*\/)
replace all with no-space-character or nothing literally

также связанные с темой: Eclipse, поиск и замена регулярных выражений

Я редактировал регулярное выражение и тестировал его: http://regex101.com/r/sU4vI2 Не уверен, что он работает в вашем случае.

Ответ 5

Существует плагин, который делает это одним щелчком мыши. Это будет комментарий/Удалить все System.Out's.

Обратитесь this, this и this.

Ответ 6

Eclipse имеет несколько ярлыков для комментирования/расторжения кода.

Для однострочного кода java-кода: Ctrl + / (перемотка вперед) и

Раскол одной строки: Ctrl + \ (обратная косая черта)

Для нескольких строк кода java-кода: Ctrl + Shift + / (Наклон вперед) и

Многострочный раскоммент: Ctrl + Shift + \ (обратная косая черта)

Примечание. Для многострочных комментариев выберите все строки, которые вы хотите сначала комментировать/раскомментировать.

Также Ctrl + Shift + L откроет список всех основных ярлыков для Eclipse.

Ответ 7

Вы можете попробовать использовать uncrustify (http://uncrustify.sourceforge.net/), чтобы переформатировать ваш /* block comments */ в // double-slash comments

Это сделает ваше регулярное выражение "более безопасным" - просто найдите строки \*s// и удалите их (простая операция sed)

Ответ 8

Это хорошо работает для меня... Я добавил его как шаблон поиска IntelliJ IDEA для комментариев JavaDoc и/или одной строки.

(?sm)(^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))|(?://).*?(?<=$))

Определение


    Options: ^ and $ match at line breaks

    Match the remainder of the regex with the options: dot matches newline (s); ^ and $ match at line breaks (m) «(?sm)»
    Match the regular expression below and capture its match into backreference number 1 «(^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))|(?://).*?(?<=$))»
       Match either the regular expression below (attempting the next alternative only if this one fails) «^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))»
          Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
          Match the regular expression below «(?:\s*)?»
             Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
             Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.) «\s*»
                Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
          Match the regular expression below and capture its match into backreference number 2 «((?:/\*(?:\*)?).*?(?<=\*/))»
             Match the regular expression below «(?:/\*(?:\*)?)»
                Match the character "/" literally «/»
                Match the character "*" literally «\*»
                Match the regular expression below «(?:\*)?»
                   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
                   Match the character "*" literally «\*»
             Match any single character «.*?»
                Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
             Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\*/)»
                Match the character "*" literally «\*»
                Match the character "/" literally «/»
       Or match regular expression number 2 below (the entire group fails if this one fails to match) «(?://).*?(?<=$)»
          Match the regular expression below «(?://)»
             Match the characters "//" literally «//»
          Match any single character «.*?»
             Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
          Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=$)»
             Assert position at the end of a line (at the end of the string or before a line break character) «$»

Ответ 9

Я сделал это с помощью команды Ctrl+F и этого регулярного выражения.

Это заменит //comments

//(.?+)+

введите описание изображения здесь