Replace "\" to a String - java

I have a URL string
http:\/\/a0.twimg.com\/profile_images\/2170585961\/ETimes_normal.png
I want replace "\" by "" but I use:
String.replaceAll("\","");
And it display error. How do i must?
(Retreived from this url key profile_image_url)

Escape the backslash with another backslash:
String.replaceAll("\\\\","");
As the first argument is a regular expression, there should be two backslashes (\ is a special character in regex). But it's also a string, so each backslash should be escaped. So there are four \s.

Use String.replace(CharSequence, CharSequence) instead, it repleaces all occurrences!
str = str.replace("\\", "");
From your example:
String u = "http:\\/\\/a0.twimg.com\\/profile_images\\/2170585961\\/ETimes_normal.png";
System.out.println(u.replace("\\",""));
Outputs:
http://a0.twimg.com/profile_images/2170585961/ETimes_normal.png
Note that String.replaceAll method takes a regular expression and in this case you don't need it..

Related

Regular expression to replace (") with (\")?

Why does the following not work:
String test = "hello\"world".replaceAll("\"", "\\\"");
System.out.println(test);
What I'm trying to do is replace any occurrence of " with \".
So I want to get as output:
hello\"world
Regular expressions are overkill for this.
myString.replace("\"", "\\\"")
should do just fine and is more readable to someone familiar with the core libraries.
The replace method just replaces one substring with another.
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
You need to two more \\ to escape the escape character, for a total of 5 \s.
\\ - escape the escape character
\\ - to display the character
\ - to escape the quote.
Try:
String test = "hello\"world".replaceAll("\"", "\\\\\"");
String test = "hello\"world".replaceAll("\"", "\\\\\"");
System.out.println(test);

How to replace all regex string in a String object?

For a string str_in = "instance (\\w+\\s+){0,8}deleted"; how can I extract instance and deleted by using the replaceAll function?
I tried str_in = str_in.replaceAll("(\\w+\\s+){0,8}", ""); but it didn't work.
If you, as your question states, really want to use replaceAll() instead of the (in my opinion more suitable) replace(), you can use the \Q and \E markers to match the string literally:
String str_in = "instance (\\w+\\s+){0,8}deleted";
System.out.println(str_in.replaceAll("\\Q(\\w+\\s+){0,8}\\E", ""));
prints
instance deleted
You will need to escape the single characters so that they lose their regex nature:
str_in.replaceAll("\\(\\\\w\\+\\\\s\\+\\)\\{0,8\\}", "")
Each escaping backslash needs to be escaped for itself because of the string literal.
Do you mean that (\\w+\\s+){0,8} is literally in the string, and you want to remove it? You will need to escape each \ again in your replaceAll, so that they are interpreted literally, not as part of a regex, and also the ( and {.
Use str_in.replace("(\\w+\\s+){0,8}", "");
replace()
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab"
replaceAll()
Replaces each substring of this string that matches the given regular expression with the given replacement

Java: replaceAll doesn't work well with backslash?

I'm trying to replace the beginning of a string with backslashes to something else.
For some weird reason the replaceAll function doesn't like backslashes.
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\xyz\\abc", "z:");
What should I do to solve this issue.
Thank you.
You need to double each backslash (again) as the Pattern class that is used by replaceAll() treats it as a special character:
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
A Java string treats backslash as an escape character so what replaceAll sees is: \\\\xyz\\abc. But replaceAll also treats backslash as an escape character so the regular expression becomes the characters: \ \ x y z \ a b c
Its doesn't like it because \ is the escape character in C like languages (even as an escape on this forum) Which makes it a poor choice for a file seperator but its a change they introduced in MS-DOS...
The problem you have is that you have escape the \ twice so \\host\path becomes \\\\host\\path in the string but for the regex has to be escaped again :P \\\\\\\\host\\\\path
If you can use a forward slash this is much simpler
String jarPath = "//xyz/abc/wtf/lame/";
jarPath = jarPath.replaceAll("//xyz/abc", "z:");
replaceAll() uses regexps which uses the backslash as an escape character. Moreover, Java String syntax also uses the backslash as an escape character. This means that you need to double all your backslashes to get what you want:
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
replaceAll expects a regular expression as its input string, which is then matched and replaced in every instance. A backslash is a special escape character in regular expressions, and in order to match it you need another backslash to escape it. So, to match a string with "\", you need a regular expression with '"\"`.
To match the string "\\\\xyz\\abc" you need the regular expression "\\\\\\\\xyz\\\\abc" (note an extra \ for each source \):
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
The replaceAll method uses regular expressions, which means that you have to escape slashes. In your case it might make sense to use String.replace instead:
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replace("\\\\xyz\\abc", "z:");
jarPath = jarPath.replaceAll("\\\\\\\\xyz\\\\abc", "z:");
For each '\' in your string you should put '\\' in the replaceAll method.
You can just use the replace method instead replaceAll in your use-case. If i'm not mistaken it's does not use regex.
You can use replace() method also which will remove \\\\xyz\\abc from the String
String jarPath = "\\\\xyz\\abc\\wtf\\lame\\";
jarPath = jarPath.replace("\\\\xyz\\abc", "z:");
Just got into a similar problem.
If you use backslash() in the second section of the replaceAll function, the backslashes will dissapear, to avoid that, you can use Matcher class.
String assetPath="\Media Database\otherfolder\anotherdeepfolder\finalfolder";
String assetRemovedPath=assetPath.replaceAll("\\\\Media Database(.*)", Matcher.quoteReplacement("\\Media Database\\_ExpiredAssets")+"$1");
system.out.println("ModifiedPath:"+assetRemovedPath);
Prints:
\Media Database\_ExpiredAssets\otherfolder\anotherdeepfolder\finalfolder
hope it helps!

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