Решение здесь:
public class MergeParentAndChildXPATH {
public static void main(String[] args) {
String substringToBeFound = "ABC";
String toReplayceWith = "XXX";
String xPathFromExcel = "/UTILMD/ABC/[XYZ/ABC/KLM]KLM[XYZ/ABC/[XYZ/ABC/KLM]KLM]/ABC";
System.out.println("original String\t"+xPathFromExcel);
String manupulatedString = mergeParentAndChildXPATH(substringToBeFound, toReplayceWith,xPathFromExcel);
System.out.println("manipulated String\t"+manupulatedString);
}
public static String mergeParentAndChildXPATH(String substringToBeFound, String toReplayceWith, String xPathFromExcel ) {
StringBuffer sbManipulatedString = new StringBuffer();
int lengthABC = substringToBeFound.length();
CharStack charStack = new CharStack();
String substringAfterMatch = "";
while (xPathFromExcel.indexOf(substringToBeFound)>-1) {
int matchStartsAt = xPathFromExcel.indexOf(substringToBeFound);
int matchEndssAt = xPathFromExcel.indexOf(substringToBeFound)+lengthABC;
String substringBeforeMatch = xPathFromExcel.substring(0, matchStartsAt);
substringAfterMatch = xPathFromExcel.substring(matchStartsAt+lengthABC);
String substringMatch = xPathFromExcel.substring(matchStartsAt, matchEndssAt);
// System.out.println("Loop Count\t"+loopCount);
// System.out.println("substringBeforeMatch\t"+substringBeforeMatch);
// System.out.println("substringAfterMatch\t"+substringAfterMatch);
// System.out.println("starts "+matchStartsAt+ " ends "+matchEndssAt);
// System.out.println("Output of match: "+substringMatch);
// now tokenize the string till match is reached and memorize brackets via Stack
String sTokenize = xPathFromExcel;
for (int i = 0; i < matchStartsAt; i++) {
char ch = sTokenize.charAt(0);
// System.out.println(ch);
// System.out.println(sTokenize.substring(0,1));
if (ch == '[') {
charStack.push(ch);
}
if (ch == ']') {
charStack.pop();
}
sTokenize = sTokenize.substring(1);
}//for
if (charStack.empty()) {
substringMatch = substringMatch.replaceAll(substringMatch, toReplayceWith);
}
//
sbManipulatedString.append(substringBeforeMatch + substringMatch);
// System.out.println("manipulatedString\t"+sbManipulatedString.toString());
xPathFromExcel = substringAfterMatch;
// System.out.println("remaining String\t"+substringAfterMatch);
}
return (sbManipulatedString.toString()+substringAfterMatch);
}
}
import java.util.Stack;
public class CharStack {
private Stack theStack;
CharStack() {
theStack = new Stack();
}
public char peek() {
Character temp = (Character) theStack.peek();
return temp.charValue();
}
public void push(char c) {
theStack.push(new Character(c));
}
public char pop() {
char temp = (Character) theStack.pop();
return temp;
}
public boolean empty() {
return theStack.empty();
}
}