简体   繁体   中英

C# Regex to replace invalid character to make it as perfect float number

for example if the string is "-234.24234.-23423.344" the result should be "-234.2423423423344"

if the string is "898.4.44.4" the result should be "898.4444"

if the string is "-898.4.-" the result should be "-898.4"

the result should always make scene as a double type

What I can make is this:

string pattern = String.Format(@"[^\d\{0}\{1}]", 
NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, 
NumberFormatInfo.CurrentInfo.NegativeSign);

string result = Regex.Replace(value, pattern, string.Empty); 
// this will not be able to deal with something like this "-.3-46821721.114.4"

Is there any perfect way to deal with those cases?

It's not a good idea using regex itself to achieve your goal, since regex lack AND and NOT logic for expression.

Try the code below, it will do the same thing.

var str = @"-.3-46821721.114.4";
var beforeHead = "";
var afterHead = "";

var validHead = new Regex(@"(\d\.)" /* use @"\." if you think "-.5" is also valid*/, RegexOptions.Compiled);
Regex.Replace(str, @"[^0-9\.-]", "");
var match = validHead.Match(str);

beforeHead = str.Substring(0, str.IndexOf(match.Value));
if (beforeHead[0] == '-')
{
    beforeHead = '-' + Regex.Replace(beforeHead, @"[^0-9]", "");
}
else
{
    beforeHead = Regex.Replace(beforeHead, @"[^0-9]", "");
}
afterHead = Regex.Replace(str.Substring(beforeHead.Length + 2 /* 1, if you use \. as head*/), @"[^0-9]", "");

var validFloatNumber = beforeHead + match.Value + afterHead;

String must be trimmed before operation.

It's probably a bad idea, but you can do this with regex like this:

Regex.Replace(input, @"[^-.0-9]|(?<!^)-|(?<=\..*)\.", "")

The regex matches:

[^-.0-9]    # anything which isn't ., -, or a digit.
|           # or
(?<!^)-     # a - which is not at the start of the string
|           # or
(?<=\..*)\. # a dot which is not the first dot in the string

This works on your examples, and additionally this case: "9-1.1" becomes "91.1".

You could also change (?<!^)- to (?<!^[^-.0-9]*)- if you'd like "asd-8" to become "-8" rather than "8".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM