import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = " \n"
+ " \n"
+ " (?<firstcapture> ~Start [^~]* ) #_(3) \n"
+ " (?<randomStuff> .*? ) #_(4) \n"
+ " \n"
+ " (?<loop_first> #_(5 start) \n"
+ " (?:\n"
+ " ~\n"
+ " (?: LOOP )\n"
+ " \\d [^~] \n"
+ " )\n"
+ " ( .*? ) # (1)\n"
+ " ) #_(5 end) \n"
+ " \n"
+ " (?:\n"
+ " (?<loop_middle> #_(6 start) \n"
+ " (?:\n"
+ " (?:\n"
+ " ~\n"
+ " (?: LOOP )\n"
+ " \\d [^~] \n"
+ " )\n"
+ " .*? \n"
+ " )*\n"
+ " ) #_(6 end) \n"
+ " (?<loop_last> #_(7 start) \n"
+ " (?:\n"
+ " ~\n"
+ " (?: LOOP )\n"
+ " \\d [^~] \n"
+ " )\n"
+ " ( .*? ) # (2)\n"
+ " ) #_(7 end) \n"
+ " )?\n"
+ " \n"
+ " (?<end> ~End [ ] stuff~ ) #_(8) \n";
final String string = " BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~LOOP3 hello3~End stuff~\n\n"
+ " BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~End stuff~\n\n"
+ " BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP3 hello3~End stuff~\n\n"
+ " BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~End stuff~\n";
final String subst = "${firstcapture}${randomStuff}${loop_last}${loop_middle}${loop_first}${end}";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html