Dart/Flutter – How to replace all special characters in a String

In this post, I will show you a simple example of how to replace all special characters in a String using replaceAll method and RegExp (regular expression).

Note: special characters in our case are all characters that are:

  • Not alphabets (a-z or A-Z)
  • Not numbers (0-9)
/// Replace all special characters by a dot
Future<void> main() async {
  const String text = r'abc-dfs@#$#%#$This';
  final result = text.replaceAll(RegExp('[^A-Za-z0-9]'), '.');
  print(result);
}

// Output
abc.dfs.......This

If you want to remove all special characters, just simply replace the dot in above code by an empty string:

/// Remove all special characters
Future<void> main() async {
  const String text = r'abc-dfs@#$#%#$This';
  final result = text.replaceAll(RegExp('[^A-Za-z0-9]'), '');
  print(result);
}

// Output
abcdfsThis
Tagged : / / / / / / /
Subscribe
Notify of
guest
10 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Burhan
Burhan
2 months ago

Thanks. How can we replace these characters (芒,没,卯, 脗, 脹, 脦) in the String?

Burhan
Burhan
Reply to  Phuc Tran
2 months ago

Thank you so much. One last question: How can I convert these characters (芒没卯脗脹脦) to (auiAUI) with RegEx?

Burhan
Burhan
Reply to  Phuc Tran
2 months ago

I want to get rid of accents and convert a whole string to regular letters. Looks like:

input : Sample text 芒没卯脗脹脦.
output: Sample text auiAUI

Burhan
Burhan
Reply to  Phuc Tran
2 months ago

Thanks. Best regards.

Burhan
Burhan
Reply to  Phuc Tran
2 months ago

Hello. I found a solution like this. Do you think it’s a better solution instead of one by one? What do you think?

final matchRE = RegExp(r"[芒没卯脗脹脦]");
  final replacementMap =
      Map.fromIterables("芒没卯脗脹脦".split(""), "auiAUI".split(""));

  String replaceMyChars(String input) =>
      input.replaceAllMapped(matchRE, (m) => replacementMap[m[0]]!);

  print(replaceMyChars("Sample text 芒没卯脗脹脦"));

Burhan
Burhan
Reply to  Phuc Tran
2 months ago

I used the splitMapJoin method for the loop. In that:
final matchRE = RegExp(r”[芒没卯脗脹脦]”);
final replacementMap = Map.fromIterables(“芒没卯脗脹脦”.split(“”), “auiAUI”.split(“”));

final result = ‘Sample 芒没 text 脗脹 sample 卯脦’.splitMapJoin(matchRE,
onMatch: (m) {
for (var i = 0; i < m.start; i++) {
return replacementMap[m[i]]!;
}
return '…';
});
print(result);

10
0
Would love your thoughts, please comment.x
()
x