试过这个,工作。这是一种荒谬的做法,但目前有效。
private static String normalize(String input) {
//Final string is held here
StringBuilder markerString = new StringBuilder(input);
//Look for the occurrences of startLoop-endLoop structures across lines
Pattern p1 = Pattern.compile("(startLoop.+?\\endLoop)+?",Pattern.DOTALL);
Matcher m1 = p1.matcher(markerString.toString());
while(m1.find()){
/* startLoop-endLoop structure found
* Make sure length of StringBuilder remains same
*/
markerString.setLength(input.length());
//group will now contain the matched subsequence of the full string
StringBuilder group = new StringBuilder(m1.group());
/* Look for occurrences of startLoop within the matched group
* and maintain a counter for the no of occurrences
*/
Pattern p2 = Pattern.compile("(startLoop)+?",Pattern.DOTALL);
Matcher m2 = p2.matcher(group.toString());
int loopCounter = 0;
while(m2.find()){
loopCounter++;
}
/* this takes care of the sequential loops scenario as well as matched group
* in nested loop scenario
*/
markerString.replace(m1.start(), m1.end(), m1.group().
replaceAll("setSomething", "setThisthing"));
/* For the no of times that startLoop occurred in the matched group,
* do the following
* 1. Find the next index of endLoop after the matched group's end in the full string
* 2. Read the subsequence between matched group's end and endIndex
* 3. Replace all setSomething with setThisthing in the subsequence
* 4. Replace subsequence in markerString
* 5. Decrement forCounter
*/
int previousEndIndex = m1.end();
int currentEndIndex = -1;
while(loopCounter>1){
currentEndIndex = markerString.indexOf("endLoop",previousEndIndex);
String replacerString = markerString.substring(previousEndIndex,currentEndIndex);
replacerString = replacerString.replaceAll("setSomething", "setThisThing");
markerString.replace(previousEndIndex, currentEndIndex, replacerString);
previousEndIndex = currentEndIndex+7;
loopCounter--;
}
}
input = markerString.toString();
}