首页 > 解决方案 > Flutter Unicode 撇号在字符串中

问题描述

我希望这是一个简单的问题,并且由于所有的树木,我只是没有看到森林。

我有一个颤动的字符串,而不是来自一个看起来像这样的 REST API:“这是什么?”

\u 引起了问题。

我不能在它上面做一个 string.replaceAll("\", "\") ,因为单斜杠意味着它正在寻找一个字符,这不是我需要的。

我尝试做一个 string.replaceAll(String.fromCharCode(0x92), "") 来删除它 - 那没有用。

然后我尝试使用正则表达式将其删除,例如 string.replaceAll("/(?:\)/", "") 并保留相同的单斜杠。

所以,问题是如何删除那个单斜杠,所以我可以添加一个双斜杠,或者用双斜杠替换它?

干杯

杰斯

标签: flutter

解决方案


当字符串被读取时,我假设正在发生的事情是它被解释为文字而不是它应该是什么(代码点),即 \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?

推荐阅读