Escaping * character in java - 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
}

Related

String's replaceAll() method and escape characters

The line
System.out.println("\\");
prints a single back-slash (\). And
System.out.println("\\\\");
prints double back-slashes (\\). Understood!
But why in the following code:
class ReplaceTest
{
public static void main(String[] args)
{
String s = "hello.world";
s = s.replaceAll("\\.", "\\\\");
System.out.println(s);
}
}
is the output:
hello\world
instead of
hello\\world
After all, the replaceAll() method is replacing a dot (\\.) with (\\\\).
Can someone please explain this?
When replacing characters using regular expressions, you're allowed to use backreferences, such as \1 to replace a using a grouping within the match.
This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.
Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)
The javadoc of replaceAll says:
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.
This is a formatted addendum to my comment
s = s.replaceAll("\\.", Matcher.quoteReplacement("\\"));
IS MORE READABLE AND MEANINGFUL THAN
s = s.replaceAll("\\.", "\\\\\\");
If you don't need regex for replacing and just need to replace exact strings, escape regex control characters before replace
String trickyString = "$Ha!I'm tricky|.|";
String safeToUseInReplaceAllString = Pattern.quote(trickyString);
The backslash is an escape character in Java Strings. e.g. backslash has a predefined meaning in Java. You have to use "\ \" to define a single backslash. If you want to define " \ w" then you must be using "\ \ w" in your regex. If you want to use backslash you as a literal you have to type \ \ \ \ as \ is also a escape character in regular expressions.
I believe in this particular case it would be easier to use replace instead of replace all.
Reverend Gonzo Has the correct answer when he talks about escaping the character.
Using replaceAll:
s = s.replaceAll("\\.", "\\\\\\\\");
Using replace:
s = s.replaceAll(".", "\\");
replace just takes a string to match to, not a regular expression.
I don't like this implementation of regex. We should be able to escape characters with a single '\' , not '\'. But anyway if you want to get THIS.Out_Of_That you can do:
String prefix = role.replaceFirst("(\\.).*", "");
So you get prefix = THIS;

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

Java and string split

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 "\\^".

How do I replace all "[", "]" and double quotes in Java

I'm am having difficulty using the replaceAll method to replace square brackets and double quotes. Any ideas?
Edit:
So far I've tried:
replace("\[", "some_thing") // returns illegal escape character
replace("[[", "some_thing") // returns Unclosed character class
replace("^[", "some_thing") // returns Unclosed character class
Don't use replaceAll, use replace. The former uses regular expressions, and [] are special characters within a regex.
String replaced = input.replace("]", ""); //etc
The double quote is special in Java so you need to escape it with a single backslash ("\"").
If you want to use a regex you need to escape those characters and put them in a character class. A character class is surrounded by [] and escaping a character is done by preceding it with a backslash \. However, because a backslash is also special in Java, it also needs to be escaped, and so to give the regex engine a backslash you have to use two backslashes (\\[).
In the end it should look like this (if you were to use regex):
String replaced = input.replaceAll("[\\[\\]\"]", "");
The replaceAll method is operating against Regular Expressions. You're probably just wanting to use the "replace" method, which despite its name, does replace all occurrences.
Looking at your edit, you probably want:
someString
.replace("[", "replacement")
.replace("]", "replacement")
.replace("\"", "replacement")
or, use an appropriate regular expression, the approach I'd actually recommend if you're willing to learn regular expressions (see Mark Peter's answer for a working example).
replaceAll() takes a regex so you have to escape special characters. If you don't want all the fancy regex, use replace().
String s = "[h\"i]";
System.out.println( s.replace("[","").replace("]","").replace("\"","") );
With double quotes, you have to escape them like so: "\""
In java:
String resultString = subjectString.replaceAll("[\\[\\]\"]", "");
this will replace []" with nothing.
Alternatively, if you wished to replace ", [ and ] with different characters (instead of replacing all with empty String) you could use the replaceEachRepeatedly() method in the StringUtils class from Commons Lang.
For example,
String input = "abc\"de[fg]hi\"";
String replaced = StringUtils.replaceEachRepeatedly(input,
new String[]{"[","]","\""},
new String[]{"<open_bracket>","<close_bracket>","<double_quote>"});
System.out.println(replaced);
Prints the following:
abc<double_quote>de<open_bracket>fg<close_bracket>hi<double_quote>

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