简体   繁体   English

如何限制正则表达式中的位数

[英]How to limit number of digits in regex

I'm using match to return only the numbers from the input.我正在使用 match 仅返回输入中的数字。 I need to limit the number of digits entered to 2. How can I do this?我需要将输入的位数限制为 2。我该怎么做?

 const numbers = input.match(/[0-9]+/g);

We can match on the regex pattern ^[0-9]{1,2} :我们可以匹配正则表达式模式^[0-9]{1,2}

 var input = "12345"; const numbers = input.match(/^[0-9]{1,2}/); console.log(input + " => " + numbers);

Note that we use ^[0-9]{1,2} rather than ^[0-9]{2} because perhaps the user only might enter a single digit.请注意,我们使用^[0-9]{1,2}而不是^[0-9]{2}因为用户可能只输入一个数字。

 const input = "1234567890"; const regex = /^\d{2}$/; const isTwoDigits = regex.test(input); if (isTwoDigits) { console.log("The input contains exactly 2 digits"); } else { console.log("The input does not contain exactly 2 digits"); }

Maybe you can use the attribut maxlength="2" for your imput也许您可以使用属性maxlength="2"作为输入

The simplest way to make it two numbers it to write is as two numbers让它写成两个数字的最简单方法是两个数字

const numbers = input.match(/[0-9][0-9]/g);

Snother way is to write it as numbers with count of two另一种方法是将其写为计数为 2 的数字

const numbers = input.match(/[0-9]{2}/g);

maybe you need to allow entering 1 number though也许你需要允许输入 1 个数字

const numbers = input.match(/[0-9][0-9]?/g);
const numbers = input.match(/[0-9]|[0-9][0-9]/g);
const numbers = input.match(/[0-9]{1,2}/g);

This would be your regex:这将是您的正则表达式:

const numbers = input.match(/[0-9]{1,2}/);

I will also explain few things that might be unclear from other answers.我还将解释一些其他答案可能不清楚的事情。

If you start your regex with ^ , you will get first 2 numbers only if the string starts with them:如果你用^开始你的正则表达式,只有当字符串以它们开头时你才会得到前 2 个数字:

const numbers = input.match(/^[0-9]{1,2}/);

If you append g to your regex, you will get all number pairs not just the first one如果你 append g到你的正则表达式,你会得到所有的数字对,而不仅仅是第一个

const numbers = input.match(/[0-9]{1,2}/g);

For simpler writing of regexes, I recommend using https://regex101.com as there is a real time tester and complete cheatsheet with examples.为了更简单地编写正则表达式,我建议使用https://regex101.com ,因为它有一个实时测试器和带有示例的完整备忘单。

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

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