正则表达式 - 狗尾续貂: 正则验证数字或小数,绝对有挑战

查看:136
本文介绍了正则表达式 - 狗尾续貂: 正则验证数字或小数,绝对有挑战的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

蛮有意思的一道关于正则的题

看到上面一道关于regex的题目,蛮有意思的,我使用JavaScript实现了一下,但不清楚是否有bugs,而且我还是想使用一个regex语句来实现,但百思不得其解。请教大家了。

下面是JavaScript的实现

'use strict';

function match(str) {
    let result = str || '<null>';
    if (!/^[+-]?0*(\.0*)?$/.test(str) && /^[+-]?\d*(\.\d*)?$/.test(str)) {
        result += '\t - matched';
    } else {
        result += '\t - failed';
    }

    console.log(result);
}

match('');
match('000');
match('000.');
match('000.000');
match('.00');
match('.000');
match('1.21');
match('1.212');
match('.231');
match('21.');
match('21.23');
match('0');
match('0.00');
match('0.10');
match('1');
match('100');
match('0.01');
match('0.01');

<null>     - failed
000     - failed
000.     - failed
000.000     - failed
.00     - failed
.000     - failed
1.21     - matched
1.212     - matched
.231     - matched
21.     - matched
21.23     - matched
0     - failed
0.00     - failed
0.10     - matched
1     - matched
100     - matched
0.01     - matched
0.01     - matched

解决方案

太简单了,不就是\d+(?:\.\d+)?排除掉0(\.0+)?吗

^(?!0(\.0+)?$)\d+(?:\.\d+)?$

这篇关于正则表达式 - 狗尾续貂: 正则验证数字或小数,绝对有挑战的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆