[Solved] Regex to match /src/main/{any_package}/*.java


Maybe, this expression would also function here, even though your original expression is OK.

^\/src\/main\/java(\/[^\/]+)?\/\*\.java$

Demo 1

My guess is that here we wish to pass:

/src/main/java/{any_package}/*.java
/src/main/java/*.java

If the second one is undesired, then we would simply remove the optional group:

^\/src\/main\/java(\/[^\/]+)\/\*\.java$

Demo 2

and it might still work.

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^\\/src\\/main\\/java(\\/[^\\/]+)\\/\\*\\.java$";
final String string = "/src/main/java/{any_package}/*.java\n"
     + "/src/main/java/*.java";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

solved Regex to match /src/main/{any_package}/*.java