Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66067497/dart-regexp-replace-all-but-numbers-and-allow-once-or

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...