I need to replace some of the contents of a large string with different content in the same spot.
Lets say I have a string:
String str = "package blah.foo.bar;\n"
+ "import org.blah.blah;\n"
+ "import sel.this.that;\n"
+ "import sel.boo.foo;\n"
+ "...more text";
I want to insert the word gen into statements which start with import sel. So that the end result looks like: import sel.gen.this.that;
I have had success with the following method but only when I KNOW where that substring will be within the string. My issue is that I'm not sure how to make the following code dynamic:
private String modifyString(String str){
String hold = str.substring(0, str.indexOf(";"));
hold = new StringBuilder(hold).insert(13, "gen.").toString();
str = str.replace("(?m)^package.*", hold);
return str;
}
The above code correctly replaces the strings package blah.foo.bar; with package blah.gen.foo.bar;
But again this only works with replacing the beginning portion of the string. I'm looking to be able to hold all instances of a substring and then insert a substring within those substrings.