文字列式を仮定すると、(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))
特定の深さの部分文字列 (つまり、部分式) を抽出する方法は?
検索項目が x4 の場合、部分式は(x4(x5(x6)(x7)))
、 検索項目が x5 の場合、部分式は(x5(x6)(x7))
文字列式を仮定すると、(x1(x2)(x3)(x4(x5(x6)(x7)))(x8))
特定の深さの部分文字列 (つまり、部分式) を抽出する方法は?
検索項目が x4 の場合、部分式は(x4(x5(x6)(x7)))
、 検索項目が x5 の場合、部分式は(x5(x6)(x7))
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);