Javascript 一位或两位数字正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10771269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:51:29  来源:igfitidea点击:

One or two numeric digits Regex

javascriptregexnumbersdigits

提问by CBuzatu

I have the below code. It works only when I have 2 digits. If I have 1 digit doesn't work. I want to work in both cases: one or two digit.
var numberRegex = /^[1-9][0-9]$/;
I've tried something like this but unfortunately doesn't work:
var numberRegex = /^[1-9]?[1-9][0-9]$/;
Thanks for support.

我有以下代码。仅当我有 2 位数字时才有效。如果我有 1 位数字不起作用。我想在两种情况下工作:一位或两位数。
var numberRegex = /^[1-9][0-9]$/;
我试过这样的事情,但不幸的是不起作用:
var numberRegex = /^[1-9]?[1-9][0-9]$/;
感谢支持。

回答by Joel Etherton

Try this one out:

试试这个:

/^\d{1,2}$/;

Reading what you have it looks like you don't want to accept numbers like 01.

阅读您拥有的内容,您似乎不想接受01.

/^\d{1}|[1-9]\d{1}$/;

回答by Vishak Kavalur

Try this.

尝试这个。

/^[0-9]|[0-9][0-9]$/

This should do the job. Using an Or operator does it.

这应该可以完成工作。使用 Or 运算符即可。

回答by Ozz

This works:

这有效:

/^([0-9]{0,1}([1-9][0-9]){0,2})$/

回答by Darshana

try this regex: /^[1-9]\d{0,1}$/

试试这个正则表达式: /^[1-9]\d{0,1}$/