regexdartflutter

How to remove only symbols from string in dart


I want to remove all special symbols from string and have only words in string I tried this but it gives same output only

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

output : Hello, world! i am 'foo'
expected : Hello world i am foo


Solution

  • The docs for the RegExp class state that you should use raw strings (a string literal prefixed with an r, like r"Hello world") if you're constructing a regular expression that way. This is particularly necessary where you're using escapes.

    In addition, your regex is going to catch spaces as well, so you'll need to modify that. You can use RegExp(r"[^\s\w]") instead - that matches any character that's not whitespace or a word character