[英]C# Regex to replace invalid character to make it as perfect float number
例如,如果字符串是“ -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"
有沒有完美的方式來處理這些案件?
使用正則表達式本身來實現您的目標不是一個好主意,因為正則表達式缺少表達的AND
和NOT
邏輯。
嘗試下面的代碼,它將執行相同的操作。
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;
字符串必須在操作前修剪。
這可能是個壞主意,但是您可以使用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]*)-
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.