3

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.

0

2 Answers 2

5

You can use a simple line like:

str = str.replaceAll("import sel\\.", "import sel.gen.");

Regex demo

IdeOne example

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I have been staring at this for too long!
@panthor314 glad to help.
-1

replace takes a literal string expression as an argument, not a regex.

This should work and is simpler than using a regex:

String result = str.replace("import sel.", "import sel.gen.");

Comments