Dart Regexp replace all but numbers and allow once . or , Dart Regexp replace all but numbers and allow once . or , dart dart

Dart Regexp replace all but numbers and allow once . or ,


You can use

text.replaceAllMapped(RegExp(r'^([^,.]*[.,])|\D+'), (Match m) =>    m[1] != null ? m[1].replaceAll(RegExp(r'[^0-9,.]+'), '') : '')

The ^([^.,]*[.,])|\D+ regex matches

  • ^([^,.]*[.,]) - start of string and then any chars other than , and . and then a . or , captured into Group 1
  • | - or
  • \D+ - any one or more non-digit chars.

If the first alternative matches, the , and . should be preserved, so .replaceAll(RegExp(r'[^0-9,.]+'), '') is used to remove all chars other than digits, . and ,.

If \D+ matches, it means the first . or , has already been matched, so the replacement for this alternative is an empty string.