【发布时间】:2019-03-13 19:28:22
【问题描述】:
我正在开发一个项目,该项目将通过 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 };
}
}
}
}
}
【问题讨论】:
-
这取决于......
-
对于复杂的模式,可能。对于非常简单的字符搜索,几乎可以肯定不是。
标签: java regex performance iteration