I've been trying to make a regular expression for a few hours that drives me crazy... Let's see if you can help me, please. First the code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ejercicio2_1 {
public static void main(String[] args) {
String codeJava =
"public class Ejercicio1_Math {\r\n" +
"\r\n" +
" public static void main(String[] args) {\r\n" +
" \r\n" +
" // MATH\r\n" +
" \r\n" +
" /*\r\n" +
" * 1. static float abs(float a)\r\n" +
" * 2. static int addExact(int x, int y)\r\n" +
" * 3. static double ceil (double a). Probar con positivo y negativo.\r\n" +
" * 4. static int decrementExact (int a)\r\n" +
" * 5. static double floor(double a). Probar con positivo y negativo.\r\n" +
" * 6. static int incrementExact(int a)\r\n" +
" * 7. static double max(double a, double b)\r\n" +
" * 8. static int multiplyExact(int x, int y)\r\n" +
" * 9. static int negateExact (int a)\r\n" +
" */\r\n" +
"\r\n" +
" float var_float;\r\n" +
" int var_int;\r\n" +
" double var_double;\r\n" +
";
commentOfOneLine(codeJava);
}
public static void commentOfOneLine(String string) {
int count = 0;
Pattern pattern = Pattern.compile("/\\*.*\\*/");
Matcher matcher = pattern.matcher(string);
while(matcher.find()) {
count++;
System.out.printf("Coincidencia número %d: empieza en %d y termina en %d\n", count, matcher.start(), matcher.end()-1);
}
I need to extract the index of where each block of code starts and ends.
I think the problem is that the .* grabs everything and won't let me grab the last part. */. And I don't know how to exclude that from the search.
From what I have been able to test in this way you can search with Pattern for multiline commented code:
And with this commented code only in one line:
You could try combining the two and display the results in the system.print.format.
I hope it helps.