Dart Regex: Only allow dot and numbers

Viewed 826

I need to format the price string in dart.

String can be: ₹ 2,19,990.00
String can be: $1,114.99
String can be: $14.99

What I tried:

void main() {
  String str = "₹ 2,19,990.00";
  RegExp regexp = RegExp("(\\d+[,.]?[\\d]*)");
  RegExpMatch? match = regexp.firstMatch(str);
  str = match!.group(1)!;
  print(str);
}

What my output is: 2,19
What my output is: 1,114
What my output is: 14.99

Expected output: 219990.00
Expected output: 1114.99
Expected output: 14.99 (This one is correct because there is no comma)

2 Answers

You can use this regex for search:

^\D+|(?<=\d),(?=\d)

And replace with an empty string i.e. "".

RegEx Details:

  • ^: Start
  • \D+: Match 1+ non-digit characters
  • |: OR
  • (?<=\d),(?=\d): Match a comma if it surrounded with digits on both sides RegEx Demo

Code: Using replaceAll method:

str = str.replaceAll(RegExp(r'^\D+|(?<=\d),(?=\d)'), '');

The simplest solution would be to replace all non-digit/non-dot characters with nothing.

The most efficient way to do that is:

final re = RegExp(r"[^\d.]+");
String sanitizeCurrency(String input) => input.replaceAll(re, "");

You can't do it by matching because a match is always contiguous in the source string, and you want to omit the embedded ,s.

Related