简体   繁体   中英

How to know if a regex failed on the lower or upper bound of a character size limit set with a quantifier

Quantifiers can be used in regular expressions to match strings within a size limit:

"54 343 2356 2".match(/\d{3,4}/)  // 343, 2356

If I wanted to test a string against a regex with a quantifier, how would I know if the test failed on the lower or upper bound of the character size limit?

/\d{3,4}/.test("54525")

if the test failed on the lower or upper bound of the character size limit?

For that you don't need regex, Instead do an if-else conditioning , So count number of digit in that number:

 let x = "54525"; if (x.length < 3) { console.log(x + ' has less digits than 3'); } else if (x.length > 4) { console.log(x + ' has more digits than 4'); } else { console.log(x + ' has exactly number of digits between 3 or 4'); }

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