Search code examples
regexflutterdartcurrency

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


I need to replace everything that is not a number and allow only the first , or ..

final string = _lengthController.text?.replaceAll(RegExp('[^0-9,.]'), '')

This is what I got so far and its working fine but will allow , . more than once.

So how can I replace every , and . after the first one, not one of each but only one in total is allowed.


Solution

  • 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.