Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace a Backslash

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.

like image 812
kensen john Avatar asked Apr 08 '11 14:04

kensen john


People also ask

How do you replace a single backslash in a string in Java?

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

How do you handle a backslash in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do you replace a backslash in a string Python?

To replace backslashes in a string with Python, the easiest way is to use the Python built-in string replace() function.


2 Answers

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.
like image 67
Bozho Avatar answered Sep 21 '22 03:09

Bozho


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.

like image 39
Paŭlo Ebermann Avatar answered Sep 18 '22 03:09

Paŭlo Ebermann