Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only symbols from string in dart

Tags:

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

like image 296
ketiwu Avatar asked Nov 10 '18 13:11

ketiwu


People also ask

How do you remove part of a string in flutter?

String s = "one. two"; //Removes everything after first '. ' String result = s. substring(0, s.

How do you replace a character in a string in darts?

To replace all occurrences of a substring in a string with new substring, use String. replaceAll() method. The method returns a new string with all string matchings of given pattern replaced with newSubString . You can give a string for pattern .

How do you cut Dart strings?

Dart – Trim String To trim leading and trailing spaces or white space characters of a given string in Dart, you can use trim() method of String class. String. trim() returns a new string with all the leading and trailing white spaces of this string removed.


1 Answers

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.

Fully Unicode-aware solution

Based on What's the correct regex range for javascript's regexes to match all the non word characters in any script? post, bearing in mind that \w in Unicode aware regex is equal to [\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}], you can use the following in 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 
like image 174
Wiktor Stribiżew Avatar answered Oct 19 '22 21:10

Wiktor Stribiżew