Я нашел несколько регулярных выражений, которые могут вам в этом помочь. Я нашел хороший метод сопоставления регулярных выражений здесь . Я рекомендую прочитать эти ответы. Вот моя реализация:
private static boolean validateMethodSignature(String method) {
Pattern methodPattern = Pattern.compile("(((public|private|protected|static|final|native|synchronized|abstract|transient)+\\s)+)?[\\$_\\w\\<\\>\\[\\]]*\\s+[\\$_\\w]+\\([^\\)]*\\)?(\\s*)\\{?[^\\}]*\\}?"
); // see the link i posted for more explanantion about the pattern
Matcher matcher = methodPattern.matcher(method);
if (matcher.matches()) {
int spaces = matcher.group(4).length(); // i added a fourth group to extract the spaces between the signature and the opening brackets
System.out.printf("pattern '%s' was a java method\n", method);
System.out.printf("%d spaces between method signature and opening curly braces \n",spaces);
return spaces == 1;
} else {
System.out.printf("pattern %s was not a java method \n", method);
return false;
}
}
Я сам проверил:
public static void main (String[] args) {
System.out.println(validateMethodSignature("public static void main(String args[]) {"));
System.out.println(validateMethodSignature("public void main(String args[]) {"));
System.out.println(validateMethodSignature("public static String main(int a, int b, String args[]) {"));
System.out.println(validateMethodSignature("void main(String args[]) {"));
System.out.println(validateMethodSignature("main(String args[]) {"));
System.out.println(validateMethodSignature("void main(String args[]) {"));
System.out.println(validateMethodSignature("some unkoksacoasjdpoj"));
}
Выход:
pattern 'public static void main(String args[]) {' was a java method
1 spaces between method signature and opening curly braces
true
pattern 'public void main(String args[]) {' was a java method
1 spaces between method signature and opening curly braces
true
pattern 'public static String main(int a, int b, String args[]) {' was a java method
1 spaces between method signature and opening curly braces
true
pattern 'void main(String args[]) {' was a java method
1 spaces between method signature and opening curly braces
true
pattern main(String args[]) { was not a java method
false
pattern 'void main(String args[]) {' was a java method
4 spaces between method signature and opening curly braces
false
pattern some unkoksacoasjdpoj was not a java method
false