replace "\" with "" in java - java

my question is quite simple:
how to replace "\" with "" ???
I tried this:
str.replaceAll("\\", "");
but I get en exception
08-04 01:14:50.146: I/LOG(7091): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:

It's simpler if you don't use replaceAll (which takes a regex) for this - just use replace (which takes a plain string). Don't use the regular expression form unless you really need regexes. It just makes things more complicated.
Don't forget that just calling replace or replaceAll is pointless as strings are immutable - you need to use the return result:
String replaced = str.replace("\\", "");

\\ is \ after string escaping, which is also an escape character in regex try
String newStr = str.replaceAll("\\\\", "");
(don't forget to assign the result)
Also, if you use some string as an input where a regular expression is expected, it is safer IMO to use Pattern#quote:
String newStr = str.replaceAll(Pattern.quote("\\"), "");

You should try this:
str.replaceAll("\\\\", "");
The \ has to be escaped in regex => you should write \\, and each \ has to be escaped in java => thats why we have the 4 \

Related

replace `\\r` with `\r` in string

I need to convert all the occurrences of \\r to \r in string.
My attempt is following:
String test = "\\r New Value";
System.out.println(test);
test = test.replaceAll("\\r", "\r");
System.out.println("output: " + test);
Output:
\r New Value
output: \r New Value
With replaceAll you would have to use .replaceAll("\\\\r", "\r"); because
to represent \ in regex you need to escape it so you need to use pass \\ to regex engine
but and to create string literal for single \ you need to write it as "\\".
Clearer way would be using replace("\\r", "\r"); which will automatically escape all regex metacharacters.
You will have to escape each of the \ symbols.
Try:
test = test.replaceAll("\\\\r", "\\r");
\ is used for escaping in Java - so every time you actually want to match a backslash in a string, you need to write it twice.
In addition, and this is what most people seem to be missing - replaceAll() takes a regex, and you just want to replace based on simple string substitution - so use replace() instead. (You can of course technically use replaceAll() on simple strings as well by escaping the regex, but then you get into either having to use Pattern.quote() on the parameters, or writing 4 backslashes just to match one backslash, because it's a special character in regular expressions as well as Java!)
A common misconception is that replace() just replaces the first instance, but this is not the case:
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
...the only difference is that it works for literals, not for regular expressions.
In this case you're inadvertently escaping r, which produces a carriage return feed! So based on the above, to avoid this you actually want:
String test = "\\\\r New Value";
and:
test = test.replace("\\\\r", "\\r");
Character \r is a carriage return :)
What is the difference between \r and \n?
To print \ use escape character\
System.out.println("\\");
Solution
Escape \ with \ :)
public static void main(String[] args) {
String test = "\\\\r New Value";
System.out.println(test);
test = test.replaceAll("\\\\r", "\\r");
System.out.println("output: " + test);
}
result
\\r New Value
output: \r New Value

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

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

Categories

Resources