我正在开发一个项目,该项目将通过 java 文件查找特定方法,并将该方法占用的行输出到文件中。我已经在使用 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 };
}
}
}
}
}
最佳答案
在您的特定情况下可能不是。
您按顺序扫描 Java String
一次。这比构建一个 Matcher
然后使用它来做同样的事情要快。 Matcher
也必须至少扫描一次 String
,这里面没有魔法。
在任何情况下,在进行与性能相关的优化之前,始终使用分析器(例如 VisualVM)。
一个可能更大的问题是首先使用正则表达式解析 Java。这样的解决方案不可避免地是脆弱的(例如,可以在一行中写一个Java方法,可以有嵌套类,泛型等)。
有很多Java parsers围绕它可以以更强大的方式完成工作。
关于java - 使用 Pattern/Matcher 是否比循环遍历字符串并查找字符更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149855/