如果我们假设一个String表达式(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))
,如何提取特定深度的子字符串(即子表达式)?
如果搜索项为x4,则子表达式为(x4(x5(x6)(x7)))
,或者如果搜索项为x5,则子表达式为(x5(x6)(x7))
答案 0 :(得分:1)
这可能是一个非常天真的解决方案,但如果没有更多关于你完全希望实现的细节,这就满足了你的问题:
public static String getSubExpression(String expression, String search, char open, char close) {
int idx = expression.indexOf(open + search);
if (idx == -1)
return ""; //No match was found for the search term.
int depth = 0;
StringBuilder builder = new StringBuilder();
//Loop over the rest of the string, looking for the terminating portion of the expression
for (int i = idx; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c == open) depth++; //If an open char is found, increment the depth.
if (c == close) depth--; //If a close char is found, decrement the depth.
builder.append(expression.charAt(i)); //append the character
//when depth drops back to 0 or less, we know the entire expression has been parsed.
if (depth < 1) break;
}
return builder.toString();
}
您可以按如下方式使用它:
String expression = "(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))";
System.out.println(getSubExpression(expression, "x1", '(', ')'));
System.out.println(getSubExpression(expression, "x2", '(', ')'));
System.out.println(getSubExpression(expression, "x3", '(', ')'));
System.out.println(getSubExpression(expression, "x4", '(', ')'));
System.out.println(getSubExpression(expression, "x5", '(', ')'));
System.out.println(getSubExpression(expression, "x6", '(', ')'));
System.out.println(getSubExpression(expression, "x7", '(', ')'));
System.out.println(getSubExpression(expression, "x8", '(', ')'));
(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))
(x2)
(x3)
(x4(x5(x6)(x7)))
(x5(x6)(x7))
(x6)
(x7)
(x8)
答案 1 :(得分:0)
String source = "(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))";
String searchCriteria = "x4";
// searching in the String assuming it is Mathematical expressions
int searchCriteriaCount = searchCriteria.length();
int firstMatchedCharIndex = 0;
int lastMatchedCharIndex = 0;
knowingIndex:
for(int i = 0;i < source.length();i++){
String currentSequence = source.substring(i, i+searchCriteriaCount);
if(currentSequence.equals(searchCriteria)){
firstMatchedCharIndex = i;
break knowingIndex;
}
}
char openingBracket = '(';
char closingBracket = ')';
int openingBracketsCount = 0;
int closingBracketsCount = 0;
char[] sourceChars = source.toCharArray();
fullCriteria:
for(int i = firstMatchedCharIndex-1;i<sourceChars.length;i++){
if(sourceChars[i] == openingBracket){
openingBracketsCount++;
}
if(sourceChars[i] == closingBracket){
closingBracketsCount++;
}
if(openingBracketsCount == closingBracketsCount){
lastMatchedCharIndex = i;
break fullCriteria;
}
}
String finalEquation = source.substring(firstMatchedCharIndex-1, lastMatchedCharIndex+1);
System.out.println(finalEquation);