I have large json string something like this:
[{\"name\":\"Nick\",\"role\":\"admin\",\"age\":\"32\",\"rating\":47}]
I want to remove every occurrence of \" with " in string.
for this i used String's `relaceAll("\\"","\"")
when i am print the string after replace its printing fine but when i am sending string to object in json. its appending slash , please guide me how to get rid of this slash
My expecting result:
[{"name":"Nick","role":"admin","age":"32","rating":47}]
For this i used String's relaceAll("\\"","\"") ...
The String#replaceAll() method interprets the argument as a RegEx (Regular Expression). The Backslash Character (\) is an escape character in both String & Regex.
Hence, you need to double-escape it for the RegEx to work.
Example:
myString = myString.replaceAll("\\\\", "\\\\\\\\");
You can also use String#replace() method to perfrom the same task like this:
myString = myString.replace("\\", "\\\\");
Related
I'm trying to replace \" backslash and quote to ", those characters are together in my text, so I do a replace but the compiler it say that my escaping syntax is incorrect:
String myText = "Animal:{\"name\":\"turkey\"}";
As you can observe here there is \" together so I'm want to replace by just one quote "
To look like this:
"Animal:{"name":"turkey"}"
So my replace its looks like:
myText.replaceAll("\\\"", "\"");
To escape a backslash we need \\
To escape a quote we need \"
With that logic I have this \\\" but its not working, its incorrect for the compiler...
I already tried:
myText.replaceAll("\\*", "");
But this one is not want I want in my string.
Any advice?
I think you are exposing the problem wrongly.
If you write a String like this in the source code:
String myText = "Animal:{\"name\":\"turkey\"}";
... the String is already escaped.
It means you may print :
System.out.println(myText);
... and you would get in output:
Animal:{"name":"turkey"}
... without need of doing anything else.
So I can only imagine two things:
Your question is: Can I write String myText = "Animal:{"name":"turkey"}"; without backslashes in the source code? => The answer is no, or the compiler wouldn't know what's the delimiter of the text and what's just another character of the text.
Your question is missing information: for example, you are receiving this String from a service which is responding in Json, and over the transport this String is keeping the backslashes on the quotes.
If that's the case, you should rather use the proper library to parse the message as JsonNode. Add a dependency to jackson-databind into your project and then use these methods:
ObjectMapper mapper = new ObjectMapper(); // <-- create ObjectMapper
JsonNode actualObj = mapper.readTree(jsonString); // <-- parse your Json string into a JsonNode
String niceJsonString = actualObj.toPrettyString(); // <-- formats the Json properly
If your question falls in my second guess, then I suggest you have a look at Jackson, it is a pretty powerful library to work with Json (a market standard for Json messaging in Java).
The problem is that the first argument of replaceAll is not just a String, it is a regex string, and regex also uses backslash to escape the next character. So you need another entire level of escaping, so that what you are passing to regex is the string you have, i.e. escape backslash escape quote, so that the regex will search for the sequence backslash quote.
myText.replaceAll("\\\\\\\"", "\"");
I think that's right.
I have the following code:
public static void main(String[] args) {
String str = "21.12.2015";
String delim = "\\.";
String[] st = str.split(delim);
System.out.println(st[0]+"."+st[1]+"."+st[2]); // 1
System.out.println(st[0]+delim+st[1]+delim+st[2]); // 2
}
Now, line 1 is printing expected output - 21.12.2015. But why line 2 is not giving same output as line 1? Why it is printing like 21\.12\.2015?
EDIT:
Actually in my requirement, the delimiter changes dynamically for each string(- or / or .). So I am trying to assign the delimiter to a variable and then split by it and finally print it as a pattern(say dd.mm.yy or dd-mm-yy or etc). For other delimiters it's fine, but for dot it's coming like dd\.mm\.yy. How shall I achieve the expected result?
This handles all delim values:
String str = "21.12.2015";
String delim = "."; // or "-" or "?" or ...
String[] st = str.split(java.util.regex.Pattern.quote(delim));
When you say split you are using delim as a regex pattern. It is treated differently. Please have a look to this regular expression.
But when you are using delim in sysout you are using it as string. the difference is obviuos
When you create the delim variable, you escape the backslash. The real value of the delim variable is \..
Just create the delim variable as (the backslash is useless):
String delim = ".";
because of delim = "\\.", while spliting "\\." is required.
You are using the split method from the String class, which uses regular expression for splitting the the string.
Due to this the \\. will split the string by every dot and needs to be escaped, since the dot itself is part of the regular expression.
In the second part you are simply printing the string, in which the backlash itself is a indicator for an string expression (like \n as a new line).
The double backlash just excludes this string expression to be written as a normal string "\n" in this case, and thats why you get the "\." result
For better understanding, try to delete one of the backslashes in the delim variable, and the java interpreter will throw an error since "\." is not a string expression
\\. is a regex String to parse . literally. You need it while splitting (since split() expects a regex String).
While printing, you need to use . directly isntead of "\\." because println() doesn't need a regex.
Split method uses regex for splitting so you will need to provide as \\. while this is not the scenario when you are printing it, you just need to use '.' directly.
In Java \\. will be printed as \. as \\ is considered as a single backslash.
I have a string in java that looks something like:
holdingco^(218) 333-4444^scott#holdingco.com
I set a string variable equal to it:
String value = "holdingco^(218) 333-4444^scott#holdingco.com";
Then I want to split this string into it's components:
String[] components = value.split("^");
However it does not split up the string. I have tried escaping the carrot delimiter to no avail.
Use
String[] components = value.split("\\^");
The unescaped ^ means beginning of a string in a regex, and the unescaped $ means end. You have to use two backslashes for escaping, as the string literal "\\" represents a single backslash, and that's what regex needs.
If you tried escaping with one backslash, it didn't compile, as \^ is not a valid escape sequence in Java.
try with: value.split("\\^"); this should work a bit better
I would like to remove character "|" by using String#replaceAll() method.
But first parameter is recognized regex meta character.
I tried replaceAll("\|", ""); with escape character, but it cannot be compiled.
Are there any way to remove or replace "|" character by Java?
You need to double-escape the | when using replaceAll(), like:
myString.replaceAll("\\|", "");
This is because your string actually gets parsed twice, first as a literal string and then as a regular expression. So when you start with "\\|" the first parse gives you a literal string of \|, which the regex parser then recognizes as |. This can be a bit confusing until you get used to it.
The correct answer is, don't use replaceAll() (which replaces regexes), use replace() which simply replaces a character:
replace("|", "");
fyi, despite the method name not having "all" in it, is does in fact replace all instances of the specified character.
Also, this does the job too:
String test = "Hello | Hi | Test";
System.out.println(test.replace("|", ""));
String replace method is a useful tool here. No need to use regexes.
I want to replace a special character " with \" in string.
I tried str = str.replaceAll("\"","\\\");
But this doesnt work.
The closing quotes are missing in the 2nd parameter. Change to:
str = str.replaceAll("\"","\\\\\"");
Also see this example.
String.replaceAll() API:
Replaces each substring of this string that matches the given regular
expression with the given replacement.
An invocation of this method of the form str.replaceAll(regex, repl)
yields exactly the same result as the expression
Pattern.compile(regex).matcher(str).replaceAll(repl)
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.
Btw, it is duplicated question.
You have to escape the \ by doubling it:\\
Code example:
String tt = "\\\\terte\\";
System.out.println(tt);
System.out.println(tt.replaceAll("\\\\", "|"));
This gives the following output:
\\terte\
||terte|