有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过Intellij的查找功能替换整行代码?

我试图找到一种有效的方法,通过项目中的多个文件和类从源代码中删除所有的print语句

到目前为止,我发现可以使用Ctrl+Shift+F在所有包含系统的代码中查找。出来println和Ctrl+Shift+R将代码替换为其他代码(或者在我的例子中没有),但我一直无法找到替换整行代码的方法,只能替换该行中简单的系统部分。出来普林顿

有没有一种简单的方法可以让Intellij在行尾进行选择,这样我就不必每次提到源代码就手动删除它?我在前一个线程中看到了尝试该系统。出来println(*);但这对我不起作用


共 (2) 个答案

  1. # 1 楼答案

    使用正则表达式替换为换行符

    crtlshiftr,选中“正则表达式”,然后

    Text to find: .*System\.out\.println.*[\r\n]+
    Replace with: <leave blank>
    

    .*不匹配换行符,但表达式[\r\n]匹配(在所有操作系统上)

  2. # 2 楼答案

    解决方案:

    What you are looking for is called Structural Search/Replace.

    It is not very well documented but it is Extremely Powerful once you grok it completely.

    There are a few examples in the Existing Templates that you can probably modify and learn from, the following will do what you are asking for now.

    以下是方法:

    转到菜单:Edit -> Find -> Replace Structurally并使用以下Search Template

    System.out.println($EXPRESSION$);
    

    检查Case Sensitive并使File Type=Java Source

    为所有内容将搜索的Scope设置为Project Files

    如果您想将其全部删除,只需确保Replace Template字段为空即可

    你可以用Replace Template//System.out.println($EXPRESSION$);/* System.out.println($EXPRESSION$); */来注释它们

    更好的解决方案:

    Use the Structural Search/Replace to add private static final Logger L = LoggingFactory($Class$.class); to all the classes with the System.out.println() statements.

    然后将所有System.out.println($EXPRESSION$);替换为L.info($EXPRESSION$);

    您甚至可以执行以下复杂的操作:

    这只是一个示例想法,catch的主体只需要有System.out.println($EXPRESSION$)一个更复杂的块来获取其他表达式并保存它们,这对读者来说是一个练习

    try {
      $TryStatement$;
    } catch($ExceptionType$ $ExceptionRef$) {
      System.out.println($EXPRESSION$);
    }
    

    try {
      $TryStatement$;
    } catch($ExceptionType$ $ExceptionRef$) {
      L.error($EXPRESSION$);
    }
    

    最佳解决方案:

    Always use a Logger instead of System.out.println() in everything. Even in scratch classes used for experimenting, they eventually end up in production code at some point!