Replace all special characters
Hello,
I have a little problem, after a passage a string, I realized that transformed the character & in Unicode and of course it annoys me. So I wanted to replace all the characters by their Unicode equivalent readable for the common people . So I use the replaceAll method as follows:
Code:
res = res.replaceAll("\ u003c ", "<");
Basically, I want to replace all the special characters. Unfortunately, nothing happens. Does any one knows how to fix the problem.
Re: Replace all special characters
Hello,
The character of a string can not be "transformed into unicode" for the good reason that the string is always Unicode (UTF-16). "\ u003c" and "<" are actually two different ratings for the same thing. I think you are confused here, I will recommend you to read the documentation on the java string and then write the code.
Re: Replace all special characters
Hello
Just have a look at the following code, it may help you.
Code:
Public static String decode(String source) {
Pattern pattern = Pattern.compiles("\\\\u ([0-9a-fA-F] (4)) ");
Matcher mat = pattern.mat(source);
if (mat.find()) {
/ / If we found at least one, you must create a StringBuffer
/ / Where we copy the new string:
StringBuffer sb = new StringBuffer(source.length());
do {
/ / Then whenever we find the block unicode:
/ / It gets the val of Unicode character
int codepoint = Integer.parseInt(mat.group(1), 16);
String val = new String(Character.toChars(codepoint));
mat.appendReplacement(sb, Matcher.quoteReplacement(val));
} while (mat.find());
/ / It copies the end of string:
mat.appendTail(sb);
/ / And it returns the new string
return sb.function toString() {
[native code]
}();
}
/ / No modification to do: it returns the chaien unchanged:
return source;
}
Re: Replace all special characters
Hi,
Great, thank you very much, exactly what I wanted. Thank you for your very quick response. You're going to say but good who try, nothing gained. In the interest of optimizing code, do you know if there is a library that already implements your code "decode ()"? Do you have any idea about this. If you know then please do post back.
Re: Replace all special characters
Hello,
I do not understand what you are trying to say. Literally, in Java, "\ u003c" and "<" are same. That is to say that when you write replaceAll ( "\ u003c", "<"), you write makes replaceAll ("<", "<"), which does nothing. It was double the \. I know some parsing libraries, and they are responsible to all these decoding own.
Re: Replace all special characters
Hello,
I took the Google library json - json-google (or gson). It is not bad at all and it does everything that I do not like json-lib (unless it is me who does not understand). I put resolved, and thank you to everyone. Is this helpful to me. What do you think. Can I go with this library. Thanks in advance.