简体   繁体   English

C#正则表达式替换无效字符以使其成为完美的浮点数

[英]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" 例如,如果字符串是“ -234.24234.-23423.344”,则结果应为“ -234.2423423423344”

if the string is "898.4.44.4" the result should be "898.4444" 如果字符串为“ 898.4.44.4”,则结果应为“ 898.4444”

if the string is "-898.4.-" the result should be "-898.4" 如果字符串为“ -898.4.-”,则结果应为“ -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. 使用正则表达式本身来实现您的目标不是一个好主意,因为正则表达式缺少表达的ANDNOT逻辑。

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来做到这一点:

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". 这适用于您的示例,此外,这种情况下:“ 9-1.1”变为“ 91.1”。

You could also change (?<!^)- to (?<!^[^-.0-9]*)- if you'd like "asd-8" to become "-8" rather than "8". 如果您希望将“ asd-8”变为“ -8”而不是“ 8”,也可以将(?<!^)-更改为(?<!^[^-.0-9]*)-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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