【问题标题】:How to remove only symbols from string in dart如何从飞镖中的字符串中仅删除符号
【发布时间】:2019-04-13 20:21:28
【问题描述】:

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

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

输出:Hello, world! i am 'foo'
预期:Hello world i am foo

【问题讨论】:

    标签: regex dart flutter


    【解决方案1】:

    The docs for the RegExp class 声明你应该使用 raw 字符串(以r 为前缀的字符串文字,如@9​​87654323@),如果你以这种方式构造正则表达式。这在您使用转义时尤其必要。

    此外,您的正则表达式也会捕获空格,因此您需要对其进行修改。您可以改用RegExp(r"[^\s\w]") - 匹配任何不是空格或单词字符的字符

    【讨论】:

    • 谢谢,但它也删除了空格你能告诉我如何不删除空格吗?
    【解决方案2】:

    有两个问题:

    • '\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 i am 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
    

    【讨论】:

    • 工作并在最后添加了 .replaceall("_","")
    • @RajeshJr。您可以将其合并到 1 个正则表达式中:.replaceAll(new RegExp(r'(?:_|[^\w\s])+', '')
    • 简单,但它也会取代非英语的“LETTERS”
    • @EhabReda 已更新为完全支持 Unicode 的解决方案。
    【解决方案3】:

    我发现这个问题是为了寻找如何从字符串中删除符号。对于其他想要这样做的人:

    final myString = 'abc=';
    final withoutEquals = myString.replaceAll(RegExp('='), ''); // abc
    

    【讨论】:

    • 我在替换 '.' 时得到了不好的结果在一串数字“32.151”中带有''
    • @A.easazadeh,这是因为.点字符在正则表达式中表示match any single character。因此,在您的示例中,每个字符都被匹配和替换。如果您只想匹配文字 . 点,则需要将其转义为 RegExp('\\.')RegExp(r'\.')RegExp('[.]')
    【解决方案4】:

    从字符串中删除字符“,”:

    String myString = "s, t, r";
    myString = myString.replaceAll(",", ""); // myString is "s t r"
    

    【讨论】:

      【解决方案5】:

      第一个解决方案

      s.replaceAll(RegExp(",|!|'"), "");    // The | operator works as OR
      

      第二个解决方案

      s.replaceAll(",", "").replaceAll("!", "").replaceAll("'", "");
      

      【讨论】:

        猜你喜欢
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-24
        • 2016-11-22
        • 2017-03-19
        相关资源
        最近更新 更多