regex - 如何从 Dart 中的字符串中仅删除符号

我想从字符串中删除所有特殊符号,并且字符串中只有单词 我试过了,但它只给出相同的输出

main() {
    String s = "Hello, world! i am 'foo'";
    print(s.replaceAll(new RegExp('\W+'),'')); 
}

输出:你好,世界!我是'foo'
预期:Hello world,我是 foo

最佳答案

有两个问题:

  • '\W' 不是有效的转义序列,要在常规字符串文字中定义反斜杠,您需要使用 \\,或者使用 raw 字符串文字(r'...')
  • \W 正则表达式模式匹配任何不是单词字符的字符,包括空格,您需要使用带有单词和空格类的否定字符类,[^\w\s] .

使用

void main() {
  String s = "Hello, world! i am 'foo'";
  print(s.replaceAll(new RegExp(r'[^\w\s]+'),''));
}

输出:Hello world,我是 foo.

完全支持 Unicode 的解决方案

基于 What's the correct regex range for javascript's regexes to match all the non word characters in any script?帖子,请记住 Unicode 感知正则表达式中的 \w 等于 [\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control }],你可以在 Dart 中使用以下代码:

void main() {
  String s = "Hęllo, wórld! i am 'foo'";
  String regex = r'[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}\s]+';
  print(s.replaceAll(RegExp(regex, unicode: true),''));
}
// => Hęllo wórld i am foo

https://stackoverflow.com/questions/53239702/

相关文章:

flutter - 如何在 Flutter 中将一个小部件放在另一个小部件之上?

dart - 长文本 flutter 中的换行符

dart - 全宽按钮,如何对齐文本

dart - Flutter - 是否可以在不使用 FutureBuilder 的情况下从 Futu

loops - 从 List.map() 获取迭代索引

flutter - 如何拉伸(stretch)图标以填充父级?

flutter - 如何像在 Hamilton Flutter 应用程序中一样在 Flutter 中

android - 什么时候在 Flutter 中使用 setState?

dart - Flutter Android PreferenceScreen 设置页面

dart - flutter 测试 : Waiting for a certain duration