我需要清理一个具有转义字符但不能这样做的字符串。
这是我的测试代码:
test('Replace unicode escape character', () {
String originalText = 'Jeremiah 52:1\\u201334';
String replacedText = originalText.replaceAll(r'\\', r'\');
expect(replacedText, 'Jeremiah 52:1\u201334');
});
它失败并显示错误:Expected: 'Jeremiah 52:1–34'
Actual: 'Jeremiah 52:1\\u201334'
Which: is different.
Expected: ... miah 52:1–34
Actual: ... miah 52:1\\u201334
最佳答案
Unicode字符和转义字符不会按照编写字符串时的方式存储,而是会转换为它们自己的值。当您运行以下代码时,这是显而易见的:
print('\\u2013'.length); // Prints: 6
print('\u2013'.length); // Prints: 1
在这里,发生了什么事:第一个存储了以下字符:'\','u','2','0','1'和'3'-而后者仅存储了“-”。因此,您尝试通过用一个斜杠
\\
替换两个斜杠\
来更改第一个的尝试将不起作用,因为编译器不再转换您的unicode转义字符。但这并不意味着您将无法将Unicode代码转换为Unicode字符。您可以使用以下代码:
final String str = 'Jeremiah 52:1\\u2013340';
final Pattern unicodePattern = new RegExp(r'\\u([0-9A-Fa-f]{4})');
final String newStr = str.replaceAllMapped(unicodePattern, (Match unicodeMatch) {
final int hexCode = int.parse(unicodeMatch.group(1), radix: 16);
final unicode = String.fromCharCode(hexCode);
return unicode;
});
print('Old string: $str');
print('New string: $newStr');
关于dart - 如何在Dart中替换Unicode转义字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64696536/