Search code examples
javareplaceall

Escaping space and equal to character


I am using java and have string which could have multiple spaces and equal to "=" sign as shown below.

String temp = "[name='FPC:CPU']/XM chip/allocate";

This temp string will passed to some other program which is failing because of space and equal sign.

How can i escape space and "=" character?

My desired out put from original string

[name='FPC:CPU']/XM chip/allocate 

to 

[name\='FPC:CPU']/XM\ chip/allocate  

Wondering how can i do that using temp.replaceAll


Solution

  • That should be pretty straight forward.

    System.out.println("foo bar=baz".replaceAll("([ =])" "\\\\$1"));
    

    Should print this

    foo\ bar\=baz
    

    The parenthesis in the regular expression form a capturing group, and the character class [ =] will capture spaces and equal signs.

    In the replace expression, the $1 refers to the first capturing group. The only thing that gets a bit tricky is escaping the backslash.

    Normally, in a regular expression replacement the backslash itself is an escape character. So you'd need two of them together to insert a backslash, however backslash is also an escape in a Java String, so to put two backslashes into a Java String (to form the regular expression escape), you must insert four backslashes. So that's how you end up with "\\$1".