I am creating some java code that takes correctly written .java files as input, and i want to extract the text between braces using a regular expression. I want to use the Pattern and Matcher classes, and not for loops.
I believe its best to create a regex that groups the text in the whole class, and later another regex that will be aplied to the previous output and groups the text in methods.
I got close to getting the class text using the following regex on online regex testers:
\w\sclass.*\{((.*\s*)*)\}
but i'm pretty sure i am doing it wrong by using two groups instead of just one. Furthermore when i use this expression in Java i am actually getting nothing.
Here is an example file that i am using for debugging
package foo.bar;
import java.io.File;
public class Handy {
{
// static block, dont care!
}
/**
* Check if a string is Null and Empty
* @param str
* @return
*/
public static boolean isNullOrEmpty(String str) {
Boolean result = (str == null || str.isEmpty());
return result;
}
/**
* Mimics the String.format method with a smaller name
* @param format
* @param args
* @return
*/
public static String f(String format, Object... args)
{
return String.format(format, args);
}
}
With the example code above, i expect to get:
- entire class text
{
// static block, dont care!
}
/**
* Check if a string is Null and Empty
* @param str
* @return
*/
public static boolean isNullOrEmpty(String str) {
Boolean result = (str == null || str.isEmpty());
return result;
}
/**
* Mimics the String.format method with a smaller name
* @param format
* @param args
* @return
*/
public static String f(String format, Object... args)
{
return String.format(format, args);
}
- individual method text
Boolean result = (str == null || str.isEmpty());
return result;
return String.format(format, args);
I know how to use the Pattern and Matcher classes already, i just need the right regexes...