0

I am having below code

String outputStr = "-XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file=\"E:Java\\jmx-management\\jmxremote.password\" -Djava.awt.headless=true";

outputStr.replaceAll("-Dcom.sun.management.jmxremote.password.file=[\"\\w\\=\\.\\!\\#\\$\\%\\&\\*\\+\\-\\~\\:\\;\\,\\@\\|\\\\\\/]+",
    "-Dcom.sun.management.jmxremote.password.file=\"E:\\Java\\jmx-management\\jmxremote.password\"");

It is giving me

-XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file="E:Javajmx-managementjmxremote.password" -Djava.awt.headless=true

And I want this

-XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file="E:\Java\jmx-management\jmxremote.password" -Djava.awt.headless=true

without changing in replaceall

"-Dcom.sun.management.jmxremote.password.file=\"E:\\Java\\jmx-management\\jmxremote.password\""
2
  • 1
    Use 4 backslashes in the replacement string to denote 1 backslash. Apr 13, 2017 at 10:09
  • Your title refers to "forwardslash [sic]", but your code sample contains no forward slashes. WTF?
    – Lew Bloch
    Apr 13, 2017 at 14:00

2 Answers 2

1
String outputStr = "-XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file=\"E:Java\\jmx-management\\jmxremote.password\" -Djava.awt.headless=true";
outputStr = outputStr.replace("\\\\", "\\");
0

The main problem in your regex is that you need to use 4 backslashes in the Java replacement string literal to replace with 1 literal backslash. However, there are some more minor things that I'd like to comment:

  • overescaping - most of the chars in the character class can be left unescaped as they are almost all treated as literal chars in a character class,
  • the part of the pattern you want to keep can be captured and a backreference to it can be used in the replacement pattern making it shorter,
  • dots must be escaped outside a character class to denote literal dots.

See Java demo:

String outputStr = "-XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file=\"E:Java\\jmx-management\\jmxremote.password\" -Djava.awt.headless=true";
outputStr = outputStr.replaceAll("(-Dcom\\.sun\\.management\\.jmxremote\\.password\\.file=)[-\"\\w=.!#$%&*+~:;,@|\\\\/]+",
    "$1\"E:\\\\Java\\\\jmx-management\\\\jmxremote.password\"");
System.out.println(outputStr);
// => -XX:-HeapDumpOnOutOfMemoryError -XX:MaxPermSize=64m -Xms24m -Dcom.sun.management.jmxremote.password.file="E:\Java\jmx-management\jmxremote.password" -Djava.awt.headless=true

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.