gpt4 book ai didi

java - 如何打印带有缺少反斜杠的unicode字符的字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:20 25 4
gpt4 key购买 nike

我有一个字符串如下:

this is the string u00c5 with missing slash before unicode characters

它具有 unicode 字符代码,但缺少“u”之前的所有反斜杠。如何正确打印这个字符串?

我做了什么?

我尝试使用以下代码在不完整的 unicode 部分之前添加反斜杠。但是,replaceAll 中不允许使用 "\u$1"

public String sanitizeUnicodeQuirk(String input) {
try {
// String processedInput = input.replaceAll("[uU]([0123456789abcdefABCDEF]{4})", String.valueOf(Integer.parseInt("$1", 16))); // $1 is taken literally which makes valuOf and parseInt useless
String processedInput = input.replaceAll("[uU]([0123456789abcdefABCDEF]{4})", "\\\\u$1"); // Cannot make "\u$1"
String newInput = new String(processedInput.getBytes(), "UTF-8");
return newInput;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

return input;
}

最佳答案

哎呀。使用 @AlastairMcCormack 在评论中提供的可能重复链接进行概念证明:

public class Test {
public static void main(String[] args) {
String input = "this is the string u0075u0031u0032u0033u0034 with missing slash before unicode characters";
System.out.println("Original input: " + input);
Pattern pattern = java.util.regex.Pattern.compile("[uU][0-9a-fA-F]{4}");
Matcher matcher = pattern.matcher(input);
StringBuilder builder = new StringBuilder();
int lastIndex = 0;
while (matcher.find()) {
String codePoint = matcher.group().substring(1);
System.out.println("Found code point: " + codePoint);
Character charSymbol = (char) Integer.parseInt(codePoint, 16);
builder.append(input.substring(lastIndex, matcher.start()) + charSymbol);
lastIndex = matcher.end();
}
builder.append(input.substring(lastIndex));
System.out.println("Modded input: " + builder.toString());
}
}

产量:

Original input: this is the string u0075u0031u0032u0033u0034 with missing slash before unicode characters
Found code point: 0075
Found code point: 0031
Found code point: 0032
Found code point: 0033
Found code point: 0034
Modded input: this is the string u1234 with missing slash before unicode characters

代码点被编码为字符串确实有意义,并且使用正则表达式进行任何简单的清理都无法解决这个问题。这不太漂亮,所以如果有人有其他方法,我也会很高兴。

关于java - 如何打印带有缺少反斜杠的unicode字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com