C#Regex替换无效字符,使其成为完美的浮点数

本文关键字:完美 浮点数 替换 无效 字符 C#Regex | 更新日期: 2023-09-27 18:28:37

例如,如果字符串为"-234.2234.-23423.344"结果应该是"-234.223423423344"

如果字符串为"89.4.44.4"结果应该是"898.4444"

如果字符串为"-898.4.-"结果应该是"-88.4"

结果应该总是使场景成为双重类型的

我能做的是:

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"

有什么完美的方法来处理这些案件吗?

C#Regex替换无效字符,使其成为完美的浮点数

这可能是个坏主意,但您可以使用这样的regex:

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

正则表达式匹配:

[^-.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

这适用于您的示例,此外,这种情况:"9-1.1"变为"91.1"。

如果希望"asd-8"变为"-8"而不是"8",也可以将(?<!^)-更改为(?<!^[^-.0-9]*)-

使用正则表达式本身来实现目标不是一个好主意,因为正则表达式缺少ANDNOT逻辑。

试试下面的代码,它会做同样的事情。

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;

操作前必须修剪字符串。