简体   繁体   English

正则表达式只允许 10 位以下的数字?

[英]Regex to only allow numbers under 10 digits?

I'm trying to write a regex to verify that an input is a pure, positive whole number (up to 10 digits, but I'm applying that logic elsewhere).我正在尝试编写一个正则表达式来验证输入是否为纯正整数(最多 10 位,但我正在其他地方应用该逻辑)。

Right now, this is the regex that I'm working with (which I got from here ):现在,这是我正在使用的正则表达式(我从这里得到):

 ^(([1-9]*)|(([1-9]*).([0-9]*)))$

In this function:在这个函数中:

if (/^(([1-9]*)|(([1-9]*).([0-9]*)))$/.test($('#targetMe').val())) {
            alert('we cool')
        } else {
            alert('we not')
        }

However, I can't seem to get it to work, and I'm not sure if it's the regex or the function.但是,我似乎无法让它工作,我不确定它是正则表达式还是函数。 I need to disallow %, .我需要禁止 %, 。 and ' as well.和 ' 也是。 I only want numeric characters.我只想要数字字符。 Can anyone point me in the right direction?任何人都可以指出我正确的方向吗?

You can do this way:你可以这样做:

/^[0-9]{1,10}$/

Code:代码:

var tempVal = $('#targetMe').val();
if (/^[0-9]{1,10}$/.test(+tempVal)) // OR if (/^[0-9]{1,10}$/.test(+tempVal) && tempVal.length<=10) 
  alert('we cool');
else
  alert('we not');

Refer LIVE DEMO参考现场演示

var value = $('#targetMe').val(),
    re    = /^[1-9][0-9]{0,8}$/;

if (re.test(value)) {
    // ok
}

Would you need a regular expression?你需要正则表达式吗?

var value = +$('#targetMe').val();
if (value && value<9999999999) { /*etc.*/ }
  var reg      = /^[0-9]{1,10}$/;
  var checking = reg.test($('#number').val()); 

  if(checking){
    return number;
  }else{
    return false;
  }

That's the problem with blindly copying code.这就是盲目复制代码的问题。 The regex you copied is for numbers including floating point numbers with an arbitrary number of digits - and it is buggy, because it wouldn't allow the digit 0 before the decimal point.您复制的正则表达式适用于包括具有任意位数的浮点数的数字 - 它有问题,因为它不允许小数点前有数字0

You want the following regex:您需要以下正则表达式:

^[1-9][0-9]{0,9}$

Use this regular expression to match ten digits only:使用此正则表达式仅匹配十位数字:

@"^\d{10}$"

To find a sequence of ten consecutive digits anywhere in a string, use:要查找字符串中任意位置的十个连续数字的序列,请使用:

@"\d{10}"

Note that this will also find the first 10 digits of an 11 digit number.请注意,这也将查找 11 位数字的前 10 位数字。 To search anywhere in the string for exactly 10 consecutive digits.在字符串中的任意位置搜索正好 10 个连续数字。

@"(?<!\d)\d{10}(?!\d)"

check this site here you can learn JS Regular Expiration.在这里检查这个网站你可以学习 JS 定期过期。 How to create this?如何创建这个?

https://www.regextester.com/99401 https://www.regextester.com/99401

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

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