How to remove the backslash in string using regex in Java?

前端 未结 3 539
别那么骄傲
别那么骄傲 2020-11-30 06:24

How to remove the backslash in string using regex in Java?

For example:

hai how are\\ you?

I want only:

hai how are         


        
相关标签:
3条回答
  • 2020-11-30 06:54

    String foo = "hai how are\ you?"; String bar = foo.replaceAll("\\", ""); Doesnt work java.util.regex.PatternSyntaxException occurs.... Find out the reason!! @Alan has already answered.. good

    String bar = foo.replace("\\", ""); Does work

    0 讨论(0)
  • 2020-11-30 06:57
    str = str.replaceAll("\\\\", "");
    

    or

    str = str.replace("\\", "");
    

    replaceAll() treats the first argument as a regex, so you have to double escape the backslash. replace() treats it as a literal string, so you only have to escape it once.

    0 讨论(0)
  • 2020-11-30 07:08

    You can simply use String.replaceAll()

     String foo = "hai how are\\ you?";
     String bar = foo.replaceAll("\\\\", "");
    
    0 讨论(0)
提交回复
热议问题