Dart Regexp replace all but numbers and allow once . or ,
869
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.
Author by
Steven Dz
Updated on December 27, 2022Comments
-
Steven Dz over 1 year
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.-
Wiktor Stribiżew about 3 yearsI understand
r'(?<=\..*)\.|[^0-9,.]+'
won't work, right? -
Steven Dz about 3 yearsno its not working
-
-
Steven Dz about 3 yearsThanks for the fast answer, its working fine for the
.
but not working at all for the,
-
Wiktor Stribiżew about 3 years@StevenDz Can you please provide an example?
-
Wiktor Stribiżew about 3 years@StevenDz And what do you expect?
32,,43
is correctly (because you asked to "replace every,
and.
after the first one, not one of each but only one in total is allowed") converted to32,43
.321,32
must stay the same. -
Steven Dz about 3 yearsfor me its not converted (Flutter1.26.0-12.0.pre, Dart 2.12.0 )
-
Wiktor Stribiżew about 3 years@StevenDz Are you sure you are using my code? You must use raw string literals,
r'...'
, when defining the regex patterns. -
Wiktor Stribiżew about 3 years@StevenDz Ok, at any rate, my code works fine. There is something in yours that interferes with the replacing.
-
Steven Dz about 3 yearsSorry its working fine, there was another expeption thrown because its not a double with
,
and so the ui didnt updated. So I need to replace the,
with.
Thank you