Row index out of range with replace all

How to replace mapDir surrounded by <> with a specific string?

  String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
  String test = "foo: <mapDir> -bar";
  println(test.replaceAll("<mapDir>", mapDir));

      

The above is giving me a StringIndexOutOfBoundsException.

This code is below for me, but I think pure java should work too.

static String replaceWord(String original, String find, String replacement) {
    int i = original.indexOf(find);
    if (i < 0) {
        return original;  // return original if 'find' is not in it.
    }

    String partBefore = original.substring(0, i);
    String partAfter  = original.substring(i + find.length());

    return partBefore + replacement + partAfter;
}

      

+3


source to share


3 answers


You don't need the replaceAll method as you are not using regex. Instead, you can work with the replace

api as shown below:



String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replace("<mapDir>", mapDir));

      

+4


source


replaceAll

it String

uses a regex as stated in the documentation :

Note that backslashes () and dollar signs ($) in the replacement string can cause the results to differ from being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement (java.lang.String) to suppress the special meaning of these characters if necessary.

Thus, you should avoid the replacement string like this:



String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replaceAll("<mapDir>", Matcher.quoteReplacement(mapDir)));

      

which gives the result:

foo: D:\mapping\specialists\ts_gpc\ -bar

      

+3


source


Since replaceAll works with regex, you need to escape backslashes again:

String mapDir = "D:\\\\mapping\\\\specialists\\\\ts_gpc\\\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replaceAll("<mapDir>", mapDir));

      


Quoting this answer:

by the time the regex compiler sees the pattern you gave it, it only sees one backslash (since Java lexer turned the double backwhack into one)

0


source







All Articles