【问题标题】:Remove non-printable character from a string in flutter/dart从颤振/飞镖中的字符串中删除不可打印的字符
【发布时间】:2020-09-14 22:35:15
【问题描述】:

如何从 Flutter/Dart 中的字符串中删除不可打印的字符。

var c ="Maintain central project files (hard copy and electronic) for administration.â¢Perform a wide variety of administrative duties"

感谢您的帮助

【问题讨论】:

  • 您能澄清一下您要删除的内容吗?如果是 ⢠字符,那肯定是 printable (即它们不是控制字符)。如果â¢mojibake,则先用正确的编码解码字符串。

标签: flutter dart


【解决方案1】:

如果您只想保留基本 ascii 字符,您可以尝试以下操作:

  var c =
      "Maintain central project files (hard copy and electronic) for administration.â¢Perform a wide variety of administrative duties";
  var clean = c.replaceAll(RegExp(r'[^A-Za-z0-9().,;?]'), ' ');
  print(clean);

你会得到:

Maintain central project files (hard copy and electronic) for administration.  Perform a wide variety of administrative duties

调整正则表达式以包含更多或更少的字符,具体取决于您想要多少清理(比如您可以删除所有标点符号等...)

【讨论】:

    【解决方案2】:

    这是我构建的一个函数:

    /// Replaces all non-printable characters in value with a space.
    /// tabs, newline etc are all considered non-printable.
    String replaceNoPrintable(String value, {String replaceWith = ' '}) {
      var charCodes = <int>[];
    
      for (final codeUnit in value.codeUnits) {
        if (isPrintable(codeUnit)) {
          charCodes.add(codeUnit);
        } else {
          if (replaceWith.isNotEmpty) {
              charCodes.add(replaceWith.codeUnits[0]);
          }
        }
      }
    
      return String.fromCharCodes(charCodes);
    }
    
    bool isPrintable(int codeUnit) {
      var printable = true;
    
      if (codeUnit < 33) printable = false;
      if (codeUnit >= 127) printable = false;
    
      return printable;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 2020-04-08
      • 2021-09-27
      • 2020-01-03
      • 2012-06-16
      • 2020-02-13
      相关资源
      最近更新 更多