首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要一个RegExp来过滤除一个小数点以外的所有

需要一个RegExp来过滤除一个小数点以外的所有
EN

Stack Overflow用户
提问于 2014-12-23 22:09:51
回答 2查看 3.1K关注 0票数 4

我使用下面的代码来否定regexp中的字符。通过检查逆值,我可以确定输入的值是否被正确格式化。基本上,任何数字都可以允许,但只有一个小数点(放置在字符串中的任何位置)。按照我现在的方式,它捕获所有的数字,但允许多个小数点(创建无效的浮点数)。我如何调整它以捕获多个小数点(因为我只想允许一个小数点)?

代码语言:javascript
运行
复制
var regex = new RegExp(/[^0-9\.]/g);
    var containsNonNumeric = this.value.match(regex);
    if(containsNonNumeric){
        this.value = this.value.replace(regex,'');
        return false;
    }

以下是我所期待的事情:

首先,有效的输入是任意数目的数字,可能只有一个小数点。当前的行为:用户逐个输入字符,如果它们是有效字符,它们将显示出来。如果字符无效(例如字母A),字段将将该字符替换为‘’(本质上就像填充字符后的后置空间。我需要的是同样的行为,增加一个小数点太多。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-23 22:20:48

正如我理解您的问题一样,下面的代码可能是您要寻找的内容:

代码语言:javascript
运行
复制
var validatedStr=str.replace(/[^0-9.]|\.(?=.*\.)/g, "");

它替换所有字符,然后是数字和点(.),然后替换所有点,后面跟着任意数量的0-9字符,后面跟着点。

根据第一个注释进行编辑--上面的解决方案删除了除最后一点以外的所有点,作者希望删除除第一个点之外的所有内容:由于JS不支持“回头看”,解决方案可能是在regex之前反转字符串,然后再反转它,或者使用这个正则表达式:

代码语言:javascript
运行
复制
var counter=0;
var validatedStr=str.replace(/[^0-9.]|\./g, function($0){
    if( $0 == "." && !(counter++) ) // dot found and counter is not incremented
        return "."; // that means we met first dot and we want to keep it
    return ""; // if we find anything else, let's erase it
});

JFTR:counter++只在条件的第一部分是true时才会执行,所以它甚至适用于以字母开头的字符串。

票数 16
EN

Stack Overflow用户

发布于 2021-03-27 07:19:26

在@Jan的原始regex的基础上,使用一对字符串反转来处理查看后面的行为。成功地保留第一个小数点。

修改,试图覆盖底片以及。无法处理不合适的负面符号和逻辑上应该返回零的特殊情况。

代码语言:javascript
运行
复制
let keep_first_decimal = function(s) {
  return s.toString().split('').reverse().join('').replace(/[^-?0-9.]|\.(?=.*\.)/g, '').split('').reverse().join('') * 1;
};

//filters as expected
console.log(keep_first_decimal("123.45.67"));
console.log(keep_first_decimal(123));
console.log(keep_first_decimal(123.45));
console.log(keep_first_decimal("123"));
console.log(keep_first_decimal("123.45"));
console.log(keep_first_decimal("a1b2c3d.e4f5g"));
console.log(keep_first_decimal("0.123"));
console.log(keep_first_decimal(".123"));
console.log(keep_first_decimal("0.123.45"));
console.log(keep_first_decimal("123."));
console.log(keep_first_decimal("123.0"));
console.log(keep_first_decimal("-123"));
console.log(keep_first_decimal("-123.45.67"));
console.log(keep_first_decimal("a-b123.45.67"));
console.log(keep_first_decimal("-ab123"));
console.log(keep_first_decimal(""));
//NaN, should return zero?
console.log(keep_first_decimal("."));
console.log(keep_first_decimal("-"));
//NaN, can't handle minus sign after first character
console.log(keep_first_decimal("-123.-45.67"));
console.log(keep_first_decimal("123.-45.67"));
console.log(keep_first_decimal("--123"));
console.log(keep_first_decimal("-a-b123"));

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27628746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档