编辑:找到解决方案-
/**
* Returns the arguments of the method. Ensures inner methods are intact.
*
* @param fullMethod full method string
* @return arguments of the method
*/
public static String[] getArguments(String fullMethod) {
String innerFirstBrackets = fullMethod.substring(fullMethod.indexOf("(") + 1, fullMethod.lastIndexOf(")"));
if (innerFirstBrackets.contains("(") && innerFirstBrackets.contains(")")) {
List list = new List();
int count = 0;
int lastComma = 0;
for (int x = 0; x < innerFirstBrackets.length(); x++) {
if (innerFirstBrackets.charAt(x) == '(') {
count ++;
} else if (innerFirstBrackets.charAt(x) == ')') {
count --;
}
if (innerFirstBrackets.charAt(x) == ',' || x == innerFirstBrackets.length() - 1) {
if (count == 0) {
list.add(innerFirstBrackets.substring((lastComma == 0 ? -1 : lastComma) + 1,
(x == innerFirstBrackets.length() - 1 ? x + 1 : x)).trim());
lastComma = x;
}
}
}
return list.getItems();
} else {
// No inner methods
return innerFirstBrackets.split(",");
}
}
我正在尝试获取方法的 String
表示中的参数。到目前为止,我在大多数情况下都成功地做到了,但它对某些情况不起作用。
这是我目前拥有的代码:
/**
* Returns the arguments of the method. Ensures inner methods are intact.
*
* @param fullMethod full method string
* @return arguments of the method
*/
public static String[] getArguments(String fullMethod) {
String innerFirstBrackets = fullMethod.substring(fullMethod.indexOf("(") + 1, fullMethod.lastIndexOf(")"));
if (innerFirstBrackets.contains("(") && innerFirstBrackets.contains(")")) {
List list = new List();
boolean first = false, second = false;
int lastComma = 0;
for (int x = 0; x < innerFirstBrackets.length(); x++) {
if (innerFirstBrackets.charAt(x) == '(') {
first = !second;
} else if (innerFirstBrackets.charAt(x) == ')') {
second = true;
}
if (first && second) {
first = second = false;
}
if (innerFirstBrackets.charAt(x) == ',' || x == innerFirstBrackets.length() - 1) {
if (!first) {
list.add(innerFirstBrackets.substring((lastComma == 0 ? -1 : lastComma) + 1,
(x == innerFirstBrackets.length() - 1 ? x + 1 : x)).trim());
lastComma = x;
}
}
}
return list.getItems();
} else {
// No inner methods
return innerFirstBrackets.split(",");
}
}
这在有一个方法作为参数时有效,但当存在多个以方法作为参数的参数时无效。这种情况并不常见,但我不喜欢我的代码中存在漏洞。
有效方法示例
get(get(1,2));
或
get(get(get(get(1,2))));
或
get(get(1),get(1));
但是当给出这样的东西时它不会起作用
get(get(get(1)),get(1));
我不确定如何找到姊妹括号而不是仅仅找到下一个括号。 (如果你不知道我所说的姊妹括号是什么意思,想想在大多数 IDE 上,当你突出显示一个括号时,另一个会自动突出显示。例如
最佳答案
我不确定我理解为什么逗号对您的算法来说是个问题。您可以做的是开始向右扫描字符(假设您从 (
左括号开始),将计数器初始化为 0,并且:
- 每次遇到
(
时增加计数器
- 每次遇到
) 时递减计数器
当计数器再次归零时,您就找到了匹配对。您唯一需要注意的是带引号的字符串,其中代码在单引号或双引号内有随机括号(您不想将它们应用到您的计数器)。
关于java - 在字符串中查找姐妹括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967248/