【问题标题】:How to create regex for accepting only numbers and not anything else(not even spaces)?如何创建正则表达式以仅接受数字而不接受其他任何内容(甚至不接受空格)?
【发布时间】:2015-05-13 07:03:04
【问题描述】:

我看到了Regex for accepting only numbers 的问题。但这不是我想要的。

我的正则表达式接受除数字以外的任何内容并将其替换为 null。像 /[^0-9]/g 然后替换为 null 它适用于所有人空格除外。正则表达式不允许来自 a-z 或 A-Z 的任何字符或任何特殊字符。但它允许在之前或之后或中间输入空间。

var transformedInput = inputValue.replace(/[^0-9]/g, ''); 在这里,它接受除数字以外的所有字符,并将其替换为 '' 空白。但是,当我添加 space 时,它不会被替换为空白。

例如:如果我输入“a”,它将被 null 替换。 但是,如果我输入 <space>1<space>1<space> 它接受而不是用空替换空格。以下是验证:

    customValidationDirective.directive('numbersOnly', function(){
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function (inputValue) {

       if (inputValue == undefined) return '' 
       var transformedInput = inputValue.replace(/[^0-9]/g, ''); 
       if (transformedInput!=inputValue) {
          modelCtrl.$setViewValue(transformedInput);
          modelCtrl.$render();
       }         

       return transformedInput;         
       });
     }
   };
})

提前致谢。

【问题讨论】:

  • 应该可以...但可以简化为/\D/g,如' 1'.replace(/\D/g, '')
  • 那个正则表达式应该允许字母,或者任何不是数字的东西。
  • 这应该可以工作 /^[0-9]+$/gi
  • \D 或 \d 不接受除空格以外的任何内容。 :P 不是偶数。我知道为什么。我也试过了。
  • 您的代码工作正常。测试于jsfiddle

标签: javascript regex regex-negation


【解决方案1】:

在末尾添加 $ 将解决您的问题,因为它可以避免部分匹配。试试这样的。

^[0-9]*$

【讨论】:

  • 它仍在接受空间而不是替换为 '' 。 var transformInput = inputValue.replace(/[^0-9]*$/g, '');理想情况下,它应该接受除 0-9 数字之外的所有内容,并将其替换为 ''。但它不会用空格替换空格。
  • 您是否能够提供您需要的字符串类型并且目前您正在获取输入?
【解决方案2】:

JavaScript 代码

function NumberOnly(e)
 {
var key;
var keychar;

if (window.event)
    key = window.event.keyCode;
else if (e)
    key = e.which;
else
    return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27) || (key == 32))
    return true;

    // alphas and numbers
else if ((("abcdefghijklmnopqrstuvwxyz").indexOf(keychar) > -1))
    return true;
else
    return false;
}

HTML

onkeypress="return NumberOnly(event)"

【讨论】:

    【解决方案3】:

    您可以使用这个正则表达式:/[^\d]+/g。这意味着,只匹配数字而不匹配其他任何东西,它与/[0-9]+/g 相同。

    【讨论】:

    • 我添加了更多细节,请参阅。谢谢您的帮助。但是 \D 或 \d 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多