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 --
Related
I am trying to execute the following operation on a String.
if (combatLog.contains("//*name//*")) {
combatLog.replaceAll("//*name//*",glad.target.name);
}
The slashes are my attempt to escape the *, as it doesn't work without them. I have also tried one slash, and slashes on contains or replaceAll individually. Thanks
replaceAll() (counter-intuitively) takes a regex, not a string.
To escape a character for a regex, you need a double-backslash (doubled to escape the backslash from the string literal).
However, you don't want a regex. You should simply call replace() instead, which won't need any escaping.
You're using forward slashes. The backslash is the escape character. Furthermore, unless the string is being used for regex or something similar, you need not escape the *, or the / if thats what you're trying to escape.
If combatLog is a String, its contains method checks for a sequence of characters only. If you're looking for *name* in the string, you only need call combatLog.contains("*name*").
You are using forward slashes use the backslash: \ to escape characters
[edit]
also as slaks said you need to use replace() which accepts a string as input rather than a regex.
Don't forget about immutability of strings, and reassign the newly created string. Also, if your if block doesn't contain any more code, you don't need the if check at all.
You have 3 options:
if (combatLog.contains("*name*")) { // don't escape in contains()
combatLog = combatLog.replaceAll("\\*name\\*", replacement);// correct escape
}
// another regex based solution
if (combatLog.contains("*name*")) {
combatLog = combatLog.replaceAll("[*]name[*]", replacement);// character class
}
or without a regex
if (combatLog.contains("*name*")) {
combatLog = combatLog.replace("*name*", replacement);// literal string
}
split this String using function split. Here is my code:
String data= "data^data";
String[] spli = data.split("^");
When I try to do that in spli contain only one string. It seems like java dont see "^" in splitting. Do anyone know how can I split this string by letter "^"?
EDIT
SOLVED :P
This is because String.split takes a regular expression, not a literal string. You have to escape the ^ as it has a different meaning in regex (anchor at the start of a string). So the split would actually be done before the first character, giving you the complete string back unaltered.
You escape a regular expression metacharacter with \, which has to be \\ in Java strings, so
data.split("\\^")
should work.
You need to escape it because it takes reg-ex
\\^
Special characters like ^ need to be escaped with \
This does not work because .split() expects its argument to be a regex. "^" has a special meaing in regex and so does not work as you expect. To get it to work, you need to escape it. Use \\^.
The reason is that split's parameter is a regular expression, so "^" means the beginning of a line. So you need to escape to ASCII-^: use the parameter "\\^".
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
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, "\\/", "/")
I am getting some weird results when using the replaceAll method of the String class.
The string query contains the following: #cm:name:"hello"
If I say query.replaceAll(":", "\\:");
I would expect the following result: #cm\:name\:"hello"
Instead I get: #cm:name:"hello". The original content.
Don't use replaceAll(..) for non-regex replaces. Use replace(..) instead.
Then, be sure to have:
query = query.replace(":", "\\:");
because String is immutable - i.e. if you just call the method without assigning the result, you get nothing - the internal state of the object won't change.
There are two simple rules.
The Java compiler requires two blackslashes to represent a single backslash in a string literal .
Regular expressions require two backslashes to represent a single backslash in a regular expression.
So if you want a string literal to contain a regular expression single backslash you have to write four.
The escape sequence for \ is \\. So, you'd write this:
query.replaceAll(":", "\\:");
Escape the slash
query.replaceAll(":","\\:");