String replace a Backslash

2019-01-05 04:22发布

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

Input Source String:

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

In the above String I want to replace "\/" with a "/";

Expected ouput after replace:

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

I get the Source String from a third party, therefore I have control over the format of the String.

This is what I have tried

Trial 1:

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

Exception Unexpected internal error near index 1 \

Trial 2:

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

No Exception, but does not do the required replace. Does not do anything.

Trial 3:

 sVideoURL.replace("\\", "/"); 

No Exception, but does not do the required replace. Does not do anything.

8条回答
贼婆χ
2楼-- · 2019-01-05 04:43

To Replace backslash at particular location:

if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
    stringValue=stringValue.substring(0,location-1);
}
查看更多
神经病院院长
3楼-- · 2019-01-05 04:47
 sSource = StringUtils.replace(sSource, "\\/", "/")
查看更多
对你真心纯属浪费
4楼-- · 2019-01-05 04:48
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.
查看更多
等我变得足够好
5楼-- · 2019-01-05 04:48
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.

查看更多
Root(大扎)
6楼-- · 2019-01-05 04:54

you have to do

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

because the backshlash should be escaped twice one for string in source one in regular expression

查看更多
一夜七次
7楼-- · 2019-01-05 04:55

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

The problem here is that a backslash is (1) an escape-chararacter in Java-Strings, and (2) an Escape-Character in regular Expressions - each of this uses need doubling the character, in effect needing 4 \ in row.


Edit: 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.

查看更多
登录 后发表回答