javascript - 允许在正则表达式中使用减号

标签 javascript regex

我有一个正则表达式,但我不知道如何允许使用减号。我的意思是,我希望允许用户使用该符号,但它也可以是不带减号的正值。

一开始我在 JavaScript 中有这个正则表达式:

 var regex = /[0-9]|\./;

我尝试过 var regex =/\-[0-9]|\./;,但它不起作用。

这是我的 JavaScript 函数:

function isNumeric(evt,type)
{
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    if (type==1)
        var regex = /[0-9]/;
    else if (type==2)
        var regex =  /^-?[0-9]\d*(.\d+)?$/;
    else if (type==3)
        var regex = /[0-9]|\ /;

    /* 13=enter; 9=tabulation; 8et 46 supprim� et sup; 37et 39 fl�che */
    if (theEvent.keyCode == 13 ||
        theEvent.keyCode == 9  ||
        theEvent.keyCode == 8  ||
        theEvent.keyCode == 46 ||
        theEvent.keyCode == 37 ||
        theEvent.keyCode == 39 ||
        (theEvent.keyCode == 19 && type == 3))
    {
        theEvent.returnValue = true;
    }
    else if (!regex.test(key))
    {
        theEvent.returnValue = false;
        if (theEvent.preventDefault)
            theEvent.preventDefault();
    }
}

我就是这么调用它的

onKeyPress = "isNumeric(event, 2);"

最佳答案

您可以使用将减号设为可选?:

var regex = /^-?[0-9]+(\.[0-9]+)?$/;

我不确定为什么你有 |\. 它只允许输入句点。

关于javascript - 允许在正则表达式中使用减号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627517/

相关文章:

javascript - 如何使用 Vue 在 API 端点中自动监视更改?

regex - 在emacs中,如何匹配缓冲区末尾的正则表达式

javascript - 导航栏上的 2 个导航按钮(引导移动设备)

javascript - 标记未与传单 d3 中的路径正确对齐

javascript - 如何使用多个请求创建 Promise.all

正则表达式 - 将数字与常量进行比较

java - 不想匹配一个字符后跟另一个字符 - 正则表达式

javascript - 在传递给 Vue Good-Table 之前格式化列数据

regex - 使用 Grep 查找两个短语(包括短语)之间的文本 block

regex - 创建表期间解析 Hive 中的时间戳