How to replace " \ " with " \\ " in java - 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

Related

What all characters can be used as String Delimiters in Java?

I am trying break a String in various pieces using delimiter(":").
String sepIds[]=ids.split(":");
It is working fine. But when I replace ":" with " * " and use " * " as delimiter, it doesn't work.
String sepIds[]=ids.split("*"); //doesn't work
It just hangs up there, and doesn't execute further.
What mistake I am making here?
String#split takes a regular expression as parameter. In regex some chars have special meanings so they need to be escaped, for example:
"foo*bar".split("\\*")
the result will be as you expect:
[foo, bar]
You could also use the method Pattern#quote to simplify the task.
"foo*bar".split(Pattern.quote("*"))
String.split expects a regular expression argument. * has got a meaning in regex. So if you want to use them then you need to escape them like this:
String sepIds[]=ids.split("\\*");
The argument of .split() is a regular expression, not a string literal. Therefore you need to escape * since it is a special regex character. Write:
ids.split("\\*");
This is how you would split agaisnt one or more spaces:
ids.split("\\s+");
Note that Guava has Splitter which is very, very fast and can split against literals:
Splitter.on('*').split(ids);
'*' and '.' are special characters you have to blackshlash it.
String sepIds[]=ids.split("\\*");
To read more about java patterns please visit that page.
That is expected behaviour. The documentation for the String split function says that the input string is treated as a regular expression (with a link explaining how that works). As Germann points out, '*' is a special character in regular expressions.
Java's String.split() uses regular expressions to split up the string (unlike similar functions in C# or python). * is a special character in regular expressions and you need to escape it with a \ (backslash). So you should use instead:
String sepIds[]=ids.split("\\*");
You can find more information on regular expressions anywhere on the internet a quite complete list of special characters supported by java should be here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

nextLink1.replace("""), Making " act differently

nextLink1.replace(""",()), so basically I want to replace " with a blank. Any help would be greatly appreciated.
Thanks
You need to escape the " sign. Like this:
nextLink1.replace("\"","");
The compiler will recognize the first two quote marks, but the third one will produce a syntax error.
Using an escape sequence will place a double quote as such:
nextLink1.replace("\"","");
You can find more escape sequences here http://docs.oracle.com/javase/tutorial/java/data/characters.html
" is Java's metacharacter used to start or end Strings literals. If you want to use it inside String literal you need to escape it first with \ like \" (which is another Java's metacharacter used for example to create new lines mark "\n").
Also blank String is not () but "". So try this way
nextLink1.replace("\"","");
BTW Strings are immutable which means this method will not affect original String, but create new one with replaced character. If you want nextLink1 to contain String with replaced characters you will need to use
nextLink1 = nextLink1.replace("\"","");

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("\\\\"", "");

Java remove escaped double-quote

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("\\\\", "");

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 --

Categories

Resources