What regex would I use to add javadocs to a java program in vscode?

55 views Asked by At

My current attempt:
Find: (^$\n[\s]*.*\{|^$\n[\s]*.*@.*$)
Replace: /***/$1

Problem: works well except for the fact that the javadoc boilerplate is not indented.

What change would I implement to indent it accurately?


Input:


public class Main {

    class innerClass {

        int a;
        int b;

        @Override
        private int goo() {

        }
    }

    String a;

    public static void main (String[] args) {
        // blablabla
    }

    @Override
    public int foo(int a) {

    }
}

output:

/***/
public class Main {
/***/
    class innerClass {

        int a;
        int b;
/***/
        @Override
        private int goo() {

        }
    }

    String a;
/***/
    public static void main (String[] args) {
        // blablabla
    }
/***/
    @Override
    public int foo(int a) {

    }
}

Expected output:

/***/
public class Main {
    /***/
    class innerClass {

        int a;
        int b;
        /***/
        @Override
        private int goo() {

        }
    }

    String a;
    /***/
    public static void main (String[] args) {
        // blablabla
    }
    /***/
    @Override
    public int foo(int a) {

    }
}
2

There are 2 answers

8
Hao Wu On

You could try this regex

^([\s\n]*(^\s*)[^{};]*\{)

And replace it with

$2/***/$1

What it does is essentially finding all {} blocks without encountering a field(statements end with ;) and put the same length of indent within the same line of the open curly bracket and a /***/ before it.

You may see the test cases here

1
kesarling He-Him On

Apart from @HaoWu's really clever block capturing, the following works too!
Find: (^$\n([\s]*)(.*\{$|[\s]*@.*)$)
Replace: $2/***/$1