Java: replaceAll doesn't work well with backslash?

前端 未结 9 1409
北荒
北荒 2021-01-25 12:56

I\'m trying to replace the beginning of a string with backslashes to something else. For some weird reason the replaceAll function doesn\'t like backslashes.

Str         


        
9条回答
  •  一向
    一向 (楼主)
    2021-01-25 13:47

    Just got into a similar problem.

    If you use backslash() in the second section of the replaceAll function, the backslashes will dissapear, to avoid that, you can use Matcher class.

    String assetPath="\Media Database\otherfolder\anotherdeepfolder\finalfolder";
    
    String assetRemovedPath=assetPath.replaceAll("\\\\Media Database(.*)", Matcher.quoteReplacement("\\Media Database\\_ExpiredAssets")+"$1");
    
    system.out.println("ModifiedPath:"+assetRemovedPath);
    

    Prints:

    \Media Database\_ExpiredAssets\otherfolder\anotherdeepfolder\finalfolder
    

    hope it helps!

提交回复
热议问题