简体   繁体   中英

Regex returning part of match instead false when it passes the length

I want to check if a number sequence starts with 4 and have exactly 12 to 15 more digits (the number length has to have from 13 to 16 digits).

I expect my regex works returning false when it's less or greater than {12,15}.

I'm testing this regex: 4{1}\\d{12,15} that works when numbers is less than 13 digits, in this case it returns false, but when it passes from 15 digits it returns just de part of string instead be null. Ex:

With: 412345678901 preg_match() returns:

array()

With: 412345678901234567 preg_match() returns:

array(
    0 => 4123456789012345
)

In second case I wanted it to be false too, because the length is greater than 15 that I setted on Regex.

You should use anchors ^ and $ to assert the start and the end of the string.

You can omit the {1} quantifier.

^4\\d{12,15}$

 const strings = [ "4666666666666", "466666666666", "46666666666666777" ]; let pattern = /^4\\d{12,15}$/; strings.forEach((s) => { console.log(s + " ==> " + pattern.test(s)); }); 

Demo

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