flutter - Flutter Unicode 撇号在字符串中
问题描述
我希望这是一个简单的问题,并且由于所有的树木,我只是没有看到森林。
我有一个颤动的字符串,而不是来自一个看起来像这样的 REST API:“这是什么?”
\u 引起了问题。
我不能在它上面做一个 string.replaceAll("\", "\") ,因为单斜杠意味着它正在寻找一个字符,这不是我需要的。
我尝试做一个 string.replaceAll(String.fromCharCode(0x92), "") 来删除它 - 那没有用。
然后我尝试使用正则表达式将其删除,例如 string.replaceAll("/(?:\)/", "") 并保留相同的单斜杠。
所以,问题是如何删除那个单斜杠,所以我可以添加一个双斜杠,或者用双斜杠替换它?
干杯
杰斯
解决方案
当字符串被读取时,我假设正在发生的事情是它被解释为文字而不是它应该是什么(代码点),即 \0027 的每个字符都是一个单独的字符。根据您访问 API 的方式,您实际上可能能够解决此问题 - 请参阅 dart convert 库。如果您对原始数据使用 utf8.decode ,您也许可以避免整个问题。
但是,如果这不是一个选项,那么有一个足够简单的解决方案适合您。
当你写出你的正则表达式或替换时发生的事情是你没有转义反斜杠,所以它基本上什么都没有。如果您使用双斜杠,则可以解决问题,因为它会转义转义字符。"\\"
=> "\"
。
另一种选择是使用r"\"
忽略转义字符的原始字符串。
将此粘贴到https://dartpad.dartlang.org:
String withapostraphe = "What\u0027s this?";
String withapostraphe1 = withapostraphe.replaceAll('\u0027', '');
String withapostraphe2 = withapostraphe.replaceAll(String.fromCharCode(0x27), '');
print("Original encoded properly: $withapostraphe");
print("Replaced with nothing: $withapostraphe1");
print("Using char code for ': $withapostraphe2");
String unicodeNotDecoded = "What\\u0027s this?";
String unicodeWithApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '\'');
String unicodeNoApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '');
String unicodeRaw = unicodeNotDecoded.replaceAll(r"\u0027", "'");
print("Data as read with escaped unicode: $unicodeNotDecoded");
print("Data replaced with apostraphe: $unicodeWithApostraphe");
print("Data replaced with nothing: $unicodeNoApostraphe");
print("Data replaced using raw string: $unicodeRaw");
要查看结果:
Original encoded properly: What's this?
Replaced with nothing: Whats this?
Using char code for ': Whats this?
Data as read with escaped unicode: What\u0027s this?
Data replaced with apostraphe: What's this?
Data replaced with nothing: Whats this?
Data replaced using raw string: What's this?
推荐阅读
- mysql - 将数据从 MySQL 加载到 HDFS 时 Sqoop 导入错误
- spring-boot - Spring Aspect - 如何识别哪个 Pointcut 触发了函数
- c# - 使用 Datatable 和 MVVM 的 WPF 示例
- json - 我无法在 shell 中使用 jq 从 JSON 文件中获取 Key 属性值
- android - 如何更改字符串显示
- c# - ASP.NET Core Hosted 和 Server-Side Blazor 之间有什么区别,真的吗?
- windows - 我可以在 WebStorm 中打开多个终端窗口吗?如何打开?
- python-3.x - 如何修复“函数调用中缺少强制关键字参数‘size’”pylint(missing-kwoa) E1125
- angular - 以角度显示 SQL 表结果
- c# - 防止 API 中断更改