如何在 Dart 中替换 unicode 转义字符
How to replace unicode escape character in Dart
我需要清理具有转义字符但无法清理的字符串。
这是我的测试代码:
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');
我需要清理具有转义字符但无法清理的字符串。
这是我的测试代码:
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');