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

时间:2012-03-22 19:11:11

标签: c# regex

例如,如果字符串是“-234.24234.-23423.344” 结果应为“-234.2423423423344”

如果字符串是“898.4.44.4” 结果应该是“898.4444”

如果字符串是“-898.4.-” 结果应为“-898.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"

有没有完美的方法来处理这些案件?

2 个答案:

答案 0 :(得分:0)

使用正则表达式本身来实现目标并不是一个好主意,因为正则表达式缺少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;

操作前必须修剪字符串。

答案 1 :(得分:0)

这可能是一个坏主意,但你可以用这样的正则表达式来做到这一点:

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]*)-