Backslash in java - java

I have a problem with strings saved in a database, like this for example: "311\315_316\336_337". They have only one backslash and this is a problem in java. When I try to s.replaceAll("\", "\\") it doesn't work because the java compiler reads the string "311\315_316\336_337" as "311Í_316Þ_337".
I also try encoding and decoding the result of encoding "311%C3%8D_316%C3%9E_337" but the result of decoding is still "311Í_316Þ_337"?
How can I solve problem of one backslash?
I want to pass this string to function to do a process which splits numbers and the backslash is the delimiter, but this problem prevents me from doing that.

The data in the database is OK, and you don't have to replace anything. String literals, written directly in the Java code, must have their backslash escaped by another backslash:
String s = "311\\315_316\\336_337";
System.out.println(s); // prints 311\315_316\336_337
But if you get those values from the database, you don't have anything to do:
String s = resultSet.getString(1);
System.out.println(s); // should print 311\315_316\336_337

In java strings, the backslash character is a control character. If you wish to include a literal backslash in a string, you must escape it with another backslash. e.g. "\\"

in java, backslash \ has a special meaning. in order to remove it, escape it with another backslash \\
try this:
s.replaceAll("\\", "\\\\");

You could also use Unicode \ = \u005c
Example: "Folder\u005cSubfolder1\u005cSubfolder2"
Would result in the string "Folder\Subfolder1\Subfolder2"
You can see the full table here: http://jrgraphix.net/r/Unicode/0020-007F

Related

Why does .split("\\") generate an exception?

I have a String representing a directory, where \ is used to separate folders. I want to split based on "\\":
String address = "C:\\saeed\\test";
String[] splited = address.split("\\");
However, this is giving me a java.util.regex.PatternSyntaxException.
As others have suggested, you could use:
String[] separated = address.split("\\\\");
or you could use:
String[] separated = address.split(Pattern.quote("\\"));
Also, for reference:
String address = "C:\saeed\test";
will not compile, since \s is not a valid escape sequence. Here \t is interpreted as the tab character, what you actually want is:
String address = "C:\\saeed\\test";
So, now we see that in order to get a \ in a String, we need "\\". The regular expression \\ matches a single backslash since \ is a special character in regex, and hence must be escaped. Once we put this in quotes, aka turn it into a String, we need to escape each of the backslashes, yielding "\\\\".
String#split() method takes a regex. In regex, you need to escape the backslashes. And then for string literals in Java, you need to escape the backslash. In all, you need to use 4 backslashes:
String[] splited = address.split("\\\\");
\ has meaning as a part of the regex, so it too must be quoted. Try \\\\.
The Java will have at \\\\, and produce \\ which is what the regex processor needs to obtain \.
You need to use \\\\ instead of \\.
The backslash(\) is an escape character in Java Strings.If you want to use backslash as a literal you have to type \\\\ ,as \ is also a escape character in regular expressions.
For more details click here
Use separators:
String address = "C:\saeed\test";
String[] splited = address.split(System.getProperty("file.separator"));

Escaping * character in java

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
}

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

String format using java

I have to make below statement as string.i am trying,but it's giving invalid character sequence.I know it is basic,But not able to do this.any help on this appreciated.
String str="_1";
'\str%' ESCAPE '\'
Output should be: '\_1%' ESCAPE '\'.
Thanks,
Chaitu
String result = "'\\" + str + "%' ESCAPE '\\'";
Inside a string, a backslash character will "escape" the character after it - which causes that character to be treated differently.
Since \ has this special meaning, if you actually want the \ character itself in the string, you need to put \\. The first backslash escapes the second, causing it to be treated as a literal \ inside the string.
Knowing this, you should be able to construct the resulting string you need. Hope this helps.
String str="_1";
String source = "'\\str%' ESCAPE '\\'";
String result = source.replaceAll("str", str);
Another way to implement string interpolation. The replaceAll function finds all occurrences of str in the source string and replaces them by the passed argument.
To encode the backslash \ in a Java string, you have to duplicate it, because a single backslash works as an escape character.
Beware that the first argument if replaceAll is actually a regular expression, so some characters have a special meaning, but for simple words it will work as expected.
String str="_1";
String output = String.format("'\\%s%%' ESCAPE '\\'",str);
System.out.println(output);//prints '\_1%' ESCAPE '\'

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

Categories

Resources