Marco
Marco

Reputation: 593

Get only the currency symbol with a regular expression in Dart

I’m trying to get the currency symbol from a String in Dart using a regular expression:

void main() {
  const String string = '€ 1,500.50';
  final RegExp regExp = RegExp(r'([\\p{Sc}])', unicode: true);
  final Iterable<Match> matches = regExp.allMatches(string);

  final onlyCurrency = StringBuffer();
  for (final Match match in matches) {
    onlyCurrency.write(match.group(0));
  }
  
  print(onlyCurrency);
}

but this does not work. How can I get only the currency symbol (whatever it is) with a regular expression in Dart?

Thank you very much!

Upvotes: 1

Views: 413

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You need to remove the character class - it is redundant - and use \p{Sc} since you are defining the regex inside a raw string literal.

The fix is

void main() {
  const String string = '€ 1,500.50';
  final RegExp regExp = RegExp(r'\p{Sc}', unicode: true);
  final Iterable<Match> matches = regExp.allMatches(string);

  final onlyCurrency = StringBuffer();
  for (final Match match in matches) {
    onlyCurrency.write(match.group(0));
  }
  
  print(onlyCurrency);
}

Upvotes: 3

Related Questions