public static final String SEPARATOR = System.getProperty("file.separator");
 
String code = "test.foo.bar";
 
String fix = code.replaceAll("\\.", SEPARATOR);

I'm keep getting a StringIndexOutOfBoundsException. If I replace SEPARATOR with "\\\\" then it'll work as I want. Is there a safe way to replace the periods with the file separator associated with the system property?

Recommended Answers

All 2 Replies

From the Javadoc:

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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

I guess that's what you're running into.
The replacement String will need to be escaped if contains backslashes or periods.

Try using this line instead:

String fix = code.replaceAll(Character.toString('/u002e'), System.getProperty("file.separator"););
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.