简体   繁体   English

正则表达式替换不浮动的字符串

[英]Regex replace string which is not float

I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it 我有一个字符串,我需要将其解析为浮点数,但首先我需要替换它,如果它不是数字(整数或浮点数),所以我试图创建一个正则表达式来做它

My tries results in NaN 我的尝试导致NaN

One of my best tries is 我最好的尝试之一是

var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);

Can anybody tell me, what I am doing wrong? 任何人都可以告诉我,我做错了什么?

If you really want to replace everything thats not a digit, then try this: 如果你真的想要替换不是数字的所有内容,那么试试这个:

var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);

This will replace a string of "123a3d2" with a string of "12332" . 这将用字符串"123a3d2"替换字符串"123a3d2" "12332"

It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. 看起来你想在将字符串转换为float之前从字符串的开头删除“非数字”字符。 A naive approach would be: 一个天真的方法是:

var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);

This works for inputs like "foo123" but will fail on "foo.bar.123". 这适用于像“foo123”这样的输入,但在“foo.bar.123”上会失败。 To parse this we need a more sophisticated regexp: 要解析这个,我们需要一个更复杂的正则表达式:

var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);

Another method is to strip the input char by char until we find a valid float: 另一种方法是通过char去除输入char,直到找到有效的float:

function findValidFloat(str) {
    for (var i = 0; i < str.length; i++) {
        var f = parseFloat(str.substr(i))
        if (!isNaN(f))
            return f;
    }
    return NaN;
}
if (! isNaN($text))
  $float = parseFloat($text);
else
  $float = 0; // or whatever

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

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