Я работаю над проектом, который просматривает java-файл для конкретного метода и выводит строки, которые этот метод занимает в файле.Я уже использую Pattern и Matcher, чтобы найти метод, но затем я перебираю символы в строке, чтобы найти соответствующие фигурные скобки.
Мой вопрос: будет ли эффективнее использовать другой Pattern / Matcher для поиска пар фигурных скобок?
Вот метод, который находит диапазон строк для метода, если это помогает:
String line;
int currentLineNumber = 0;
int methodStart = 0;
int methodEnd = 0;
int braceCount = 0;
Matcher matcher;
while ((line = lineReader.readLine()) != null) { // Must set line's value here because readLine() increments line number
currentLineNumber = lineReader.getLineNumber();
matcher = p.matcher(line); // initialize matcher with Pattern
if (matcher.find()) { // if the line has a regex hit, store the line number as currentLine
methodStart = currentLineNumber;
}
if (currentLineNumber >= methodStart && methodStart != 0) { // make sure that we've found the method
for (int i = 0; i < line.length(); i++) { // iterates through characters in the line
/*
* Start with a braceCount of 0. When you find a starting brace, increment.
* When you find an ending brace, decrement. When braceCount reaches 0 again,
* you will know that you have reached the end of the method.
*
* Could possibly reduce complexity/increase efficiency by using set of patterns/matchers
* to find braces.
*/
if (line.charAt(i) == '{')
braceCount++;
if (line.charAt(i) == '}') {
braceCount--;
if (braceCount == 0) {
methodEnd = currentLineNumber;
return new int[] { methodStart, methodEnd };
}
}
}
}
}