简体   繁体   中英

How to limit number of digits in regex

I'm using match to return only the numbers from the input. I need to limit the number of digits entered to 2. How can I do this?

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

We can match on the regex pattern ^[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.

 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

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

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

maybe you need to allow entering 1 number though

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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