Java remove escaped double-quote - java

I have a long Java String that contains lots of escaped double-quotes:
// Prints: \"Hello my name is Sam.\" \"And I am a good boy.\"
System.out.println(bigString);
I want to remove all the escaped double-quotes (\") and replace them with normal double-quotes (") so that I get:
// Prints: "Hello my name is Sam." "And I am a good boy."
System.out.println(bigString);
I thought this was a no-brainer. My best attempt of:
bigString = bigString.replaceAll("\\", "");
Throws the following exception:
Unexpected internal error near index 1
Any ideas? Thanks in advance.

Everybody is telling you to use replaceAll, the better answer is really to use replace.
replaceAll - requires regular expression
replace [javadoc]- is just a string search and replace
So like this:
bigString = bigString.replace("\\\"", "\"");
Note that this is also faster because regular expression is not needed.

Replace all uses Regular expressions, so add another set of \\
bigString = bigString.replaceAll("\\\\\"", "\"");
Explanation why:
"\" is interpretad by java as a normal \. However if you would use only that in the parameter, it becomes the regular expression \. A \ in a regular expression escapes the next character. Since none is found, it throws an exception.
When you write in Java "\\\\\"", it is first treated by java as the regular expression \\". Which is then treated by the regular expression implementation as "a backslash followed by a double-quote".

String str="\"Hello my name is Sam.\" \"And I am a good boy.\"";
System.out.println(str.replaceAll("\\\"", "\""));
Output:
"Hello my name is Sam." "And I am a good boy."

The first argument to replaceAll is a regular expression. You pass \ which is not a valid regex. Try:
bigString.replaceAll("\\\\", "");

Related

ReplaceAll with backslashes

I want to convert all the occurences of \" in a text file into empty string.
So basically I want to convert to .
I used the following method but it doesnt seem to work:
sb.toString().replaceAll("\\"", "");
Can anyone help me with this?
sb.toString().replaceAll(Pattern.quote("\\""), "");
How about instead of replaceAll which uses regex, use simple replace which will automatically escape all regex metacharacters (like in your case "\\") in pattern you want to replace.
String replaced = sb.toString().replace("\\"", "");
Your problem is that in a regular expression, the \ character has a special meaning. You need to escape it with a second \. Then both \ characters need to be escaped from the Java compiler. You actually need to write
sb.toString().replaceAll("\\\\"", "");

String.replaceAll(...) of Java not working for \\ and \

I want to convert the directory path from:
C:\Users\Host\Desktop\picture.jpg
to
C:\\Users\\Host\\Desktop\\picture.jpg
I am using replaceAll() function and other replace functions but they do not work.
How can I do this?
I have printed the statement , it gives me the one which i wanted ie
C:\Users\Host\Desktop\picture.jpg
but now when i pass this variable to open the file, i get this exception why?
java.io.FileNotFoundException: C:\Users\Host\Desktop\picture.jpg
EDIT: Changed from replaceAll to replace - you don't need a regex here, so don't use one. (It was a really poor design decision on the part of the Java API team, IMO.)
My guess (as you haven't provided enough information) is that you're doing something like:
text.replace("\\", "\\\\");
Strings are immutable in Java, so you need to use the return value, e.g.
String newText = oldText.replace("\\", "\\\\");
If that doesn't answer your question, please provide more information.
(I'd also suggest that usually you shouldn't be doing this yourself anyway - if this is to include the information in something like a JSON response, I'd expect the wider library to perform escaping for you.)
Note that the doubling is required as \ is an escape character for Java string (and character) literals. Note that as replace doesn't treat the inputs as regular expression patterns, there's no need to perform further doubling, unlike replaceAll.
EDIT: You're now getting a FileNotFoundException because there isn't a filename with double backslashes in - what made you think there was? If you want it as a valid filename, why are you doubling the backslashes?
You have to use :
String t2 = t1.replaceAll("\\\\", "\\\\\\\\");
or (without pattern) :
String t2 = t1.replace("\\", "\\\\");
Each "\" has to be preceeded by an other "\". But it's also true for the preceeding "\" so you have to write four backslashes each time you want one in regex.
In strings \ is bydefault used as escape character therefore in order to select "\" in a string you have to use "\" and for "\" (i.e blackslack two times) use "\\". This will solve your problem and thos will also apply to other symbols also like "
Two explanations:
1. Replace double backslashes to one (not what you asked)
You have to escape the backslash by backslashes. Like this:
String newPath = oldPath.replaceAll("\\\\\\\\", "\\");
The first parameter needs to be escaped twice. Once for the Java Compiler and once because you use regular expressions. So you want to replace two backslashes by one. So, since we have to escape a backslash add one backslash. Now you have \\. This will be compiled to \. BUT!! you have to escape the backslash once again because the first parameter of the replaceAll method uses regular expressions. So to escape it, add a backslash, but that backslash needs to be escaped, so we get \\\\. These for backslashes represents one backslash in the regex. But you want to replace the double backslash to one. So use 8 backslashes.
The second parameter of the replaceAll method isn't using regular expressions, but it has to be escaped as well. So, you need to escape it once for the Java Compiler and once for the replace method: \\\\. This is compiled to two backslashes, which are being interpreted as 1 backslash in the replaceAll method.
2. Replace single backslash to a pair of backslashes (what you asked)
String newPath = oldPath.replaceAll("\\\\", "\\\\\\\\");
Same logic as above.
3. Use replace() instead of replaceAll().
String newPath = oldPath.replace("\\", "\\\\");
The difference is that the replace() method doesn't use regular expressions, so you don't have to escape every backslash twice for the first parameter.
Hopefully, I explained well...
-- Edit: Fixed error, as pointed out by xehpuk --

How to replace " \ " with " \\ " in java

I tried to break the string into arrays and replace \ with \\ , but couldn't do it, also I tried String.replaceAll something like this ("\","\\");.
I want to supply a path to JNI and it reads only in this way.
Don't use String.replaceAll in this case - that's specified in terms of regular expressions, which means you'd need even more escaping. This should be fine:
String escaped = original.replace("\\", "\\\\");
Note that the backslashes are doubled due to being in Java string literals - so the actual strings involved here are "single backslash" and "double backslash" - not double and quadruple.
replace works on simple strings - no regexes involved.
You could use replaceAll:
String escaped = original.replaceAll("\\\\", "\\\\\\\\");
I want to supply a path to JNI and it reads only in this way.
That's not right. You only need double backslashes in literal strings that you declare in a programming language. You never have to do this substitution at runtime. You need to rethink why you're doing this.
It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\" in a regex expression.
here is the link where i found this information: https://www.rgagnon.com/javadetails/java-0476.html
I had to convert '\' to '\\'. I found somewhere that we can use:
filepathtext = filepathtext.replace("\\","\\\\");
and it works.
Given below is the image of how I implemented it.
https://i.stack.imgur.com/LVjk6.png

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.
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.
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.
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 ;)
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.
This will replace backslashes with forward slashes in the string:
source = source.replace('\\','/');
you have to do
sSource.replaceAll("\\\\/", "/");
because the backshlash should be escaped twice one for string in source one in regular expression
To Replace backslash at particular location:
if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
stringValue=stringValue.substring(0,location-1);
}
sSource = StringUtils.replace(sSource, "\\/", "/")

replaceAll regular expression Replacing $

I am trying to replace all $ characters in a String expression like this
an example of a string with s$ and another with $s and here is the end.
so that the $ characters are surrounded by spaces.
I've tried string.replaceAll("$", " $ ");
This results in a illegal Argument Exception.
When I try escaping the $ character like this:
string.replaceAll("\$", " $ "); I get an invalid escape sequence error before I even build.
When I try the following:
string.replaceAll("\\$", " $ "); I get an illegal argument exception again.
Finally when I try this:
string.replaceAll("\\\\$", " $ ");
It has no effect on the string at all. I know this is something stupid that I'm just not getting. Can anyone help here?
You'll need two slashes on both sides
string.replaceAll("\\$", " \\$ ");
The first one escapes the second slash that will be passed to the regular expression. The expression is then "\$" which matches the $ sign. And you want to replace it with the same.
You have to escape the second parameter as well because allthough its not a regular expression the \ and the $ sign are a specical case here according to the documentation:
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
If you don't need parameters to be treated as regexps, use replace() instead of replaceAll() (it replaces all occurences of the first parameter as well, but doesn't treat it as regexp):
string.replace("$", " $ ");
Try string.replaceAll("\\$", " \\$ ").
The reason why you have to esacpe the $ sign in the replacement string is because the String#replaceAll() method uses Matcher#replaceAll() underneath the hood. Straight from the latter's Javadoc:
Note that backslashes (\) and
dollar signs ($) in the
replacement string may cause the
results to be different than if it
were being treated as a literal
replacement string. Dollar signs may
be treated as references to captured
subsequences as described above, and
backslashes are used to escape literal
characters in the replacement string.

Categories

Resources