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'
Hello, world! i am 'foo'
expected : Hello world i am foo
There are two issues:
'\\W'
is not a valid escape sequence, to define a backslash in a regular string literal, you need to use \\\\
, or use a raw string literal ( r'...'
) \\W
regex pattern matches any char that is not a word char including whitespace, you need to use a negated character class with word and whitespace classes, [^\\w\\s]
. Use
void main() {
String s = "Hello, world! i am 'foo'";
print(s.replaceAll(new RegExp(r'[^\w\s]+'),''));
}
Output: Hello world i am foo
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
I found this question looking for how to remove a symbol from a string. For others who come here wanting to do that:
final myString = 'abc=';
final withoutEquals = myString.replaceAll(RegExp('='), ''); // abc
Removing characters "," from string:
String myString = "s, t, r";
myString = myString.replaceAll(",", ""); // myString is "s t r"
First solution
s.replaceAll(RegExp(",|!|'"), ""); // The | operator works as OR
Second solution
s.replaceAll(",", "").replaceAll("!", "").replaceAll("'", "");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.