String replace a Backslash

前端 未结 8 856
死守一世寂寞
死守一世寂寞 2020-11-27 06:50

How can I do a string replace of a back slash.

Input Source String:

sSource = \"http://www.example.com\\/value\";

相关标签:
8条回答
  • 2020-11-27 07:00

    Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").

    The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.

    Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

    0 讨论(0)
  • 2020-11-27 07:00

    This will replace backslashes with forward slashes in the string:

    source = source.replace('\\','/');
    
    0 讨论(0)
  • 2020-11-27 07:06

    To Replace backslash at particular location:

    if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
        stringValue=stringValue.substring(0,location-1);
    }
    
    0 讨论(0)
  • 2020-11-27 07:07
    sSource = sSource.replace("\\/", "/");
    
    • String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
    • replaceAll(..) uses regex. You don't need that.
    0 讨论(0)
  • Try

       sSource = sSource.replaceAll("\\\\", "");
    

    Edit : Ok even in stackoverflow there is backslash escape... You need to have four backslashes in your replaceAll first String argument...

    The reason of this is because backslash is considered as an escape character for special characters (like \n for instance).
    Moreover replaceAll first arg is a regular expression that also use backslash as escape sequence.
    So for the regular expression you need to pass 2 backslash. To pass those two backslashes by a java String to the replaceAll, you also need to escape both backslashes.
    That drives you to have four backslashes for your expression! That's the beauty of regex in java ;)

    0 讨论(0)
  • 2020-11-27 07:09
    s.replaceAll ("\\\\", "");
    

    You need to mask a backslash in your source, and for regex, you need to mask it again, so for every backslash you need two, which ends in 4.

    But

    s = "http://www.example.com\\/value";
    

    needs two backslashes in source as well.

    0 讨论(0)
提交回复
热议问题