3

How can I replace mapDir surrounded by <> to a certain string?

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

The above gives me a StringIndexOutOfBoundsException.

This code below for me, but I think pure java has to work as well.

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;
}
clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • You need to quote (Pattern.quote) the first argument of replaceAll, as it is a regex. – Gábor Bakos Nov 22 '14 at 13:17
  • Check out this post http://stackoverflow.com/questions/18875852/why-string-replaceall-in-java-requires-4-slashes-in-regex-to-actually-r/ – gashu Nov 22 '14 at 13:38

3 Answers3

6

You dont need replaceAll method as you are not using regex. Instead you could work with replace api like below:

String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replace("<mapDir>", mapDir));
SMA
  • 36,381
  • 8
  • 49
  • 73
  • Exactly. That `all` in `replaceAll` does not mean, that it replaces all occurrences of the searched string, whereas `replace` replaces only the first one. They both replace *all* occurrences. – Tom Nov 22 '14 at 13:23
3

replaceAll in String uses a regex, as specified in the documentation:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were 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 desired.

Thus, you should escape your 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 output:

foo: D:\mapping\specialists\ts_gpc\ -bar
ebo
  • 2,717
  • 1
  • 27
  • 22
0

Since replaceAll works with regex, you need to re-escape the backslashes:

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've given it, it sees only a single backslash (since Java's lexer has turned the double backwhack into a single one)

Community
  • 1
  • 1
alterfox
  • 1,675
  • 3
  • 22
  • 37