How to replace \\ u with \ u in Java String
I have a format string:
"aaa \\ u2022bbb \\ u2014ccc"
I would like to display two special characters, but in order to do so, I must first convert the string to this format:
"aaa \ u2022bbb \ u2014ccc"
I tried writing this, but it gives a compilation error:
String encodedInput = input.replace("\\u", "\u");
It must be something straight forward, but I just can't get it. Any ideas?
source to share
Unfortunately I don't know any kind of eval.
String s = "aaa\\u2022bbb\\u2014ccc";
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(s);
while (m.find()) {
try {
int cp = Integer.parseInt(m.group(1), 16);
m.appendReplacement(buf, "");
buf.appendCodePoint(cp);
} catch (NumberFormatException e) {
}
}
m.appendTail(buf);
s = buf.toString();
source to share
In addition to escaping your screens - as other people (like barsju, for example) have pointed out - you should also consider that the usual conversion of the notation \uNNNN
to the actual Unicode character is done by the Java compiler when compiling -time.
So, even if you figured out the problem of stripping backslashes, you may have an additional problem with displaying the actual Unicode character, because you seem to be manipulating the string at runtime, not at compile time.
This answer provides a method for replacing \uNNNN
escape sequences in a runtime string with matching matching Unicode characters. Note that the method has some TODOs left in regards to error handling, bounds checking, and unexpected input.
(Edit: I think the regex-based solutions presented here, such as dash1e, would be better than the associated method as they are more polished when it comes to handling unexpected inputs).
source to share
Try
Pattern unicode = Pattern.compile("\\\\u(.{4})");
Matcher matcher = unicode.matcher("aaa\\u2022bbb\\u2014ccc");
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
int code = Integer.parseInt(matcher.group(1), 16);
matcher.appendReplacement(sb, new String(Character.toChars(code)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());
source to share