Reputation: 105
I am removing all non-numeric and non-decimal values using:
Regex.Replace("A1B2C3.D4E5F6.G7H8I9", @"[^-?\d+\.]", "");
Output: 123.456.789
The issue is the repeating decimals. I need to remove all but the first decimal.
So the output becomes: 123.456789
I've found the pattern "\.(?=.*\.)"
but it outputs 123456.789. Which is the last decimal instead of the first.
Can anyone combine these two patterns into one that will also remove repeating decimals after the first decimal? Ty
Upvotes: 2
Views: 1658
Reputation: 1430
You can do your regular expression comparison and then split the string on decimal places
string newval = Regex.Replace("A1B2C3.D4E5F6.G7H8I9", @"[^-?\d+\.]", "");
string[] tempsplit = newval.Split('.');
and then join them back together by putting a '.' between tempsplit[0] and tempsplit[1], followed by the rest of the strings in the array.
Upvotes: 3
Reputation: 354834
You can replace all but the first .
by replacing the following:
(?<=\.[^.]*)\.
which you can easily integrate into your regex:
[^-?\d+\.]|(?<=\.[^.]*)\.
This only matches a dot if there is another dot preceding. Note that this regex doesn't work on most other regex engines out there because it uses a variable-width lookbehind.
Upvotes: 2