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;
}
2
  • You need to quote (Pattern.quote) the first argument of replaceAll, as it is a regex. Commented Nov 22, 2014 at 13:17
  • Check out this post stackoverflow.com/questions/18875852/… Commented Nov 22, 2014 at 13:38

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.