I was playing with regular expression and noticed that the below code is returning true
. Can any one explain why?
console.log(/\\d{4,12}$/.test('12345678901234567890'));
How can I have limited number of digits say, 4-8(number of digits) and some alphabets in my regular expression? Ex- ('abc7896' -> true, 'a78b96' -> true, etc)
\\d{4,12}
looks if the string contains 4 to 12 digits which is correct. If you want to limit this, you can use the anchor tags - ^
for beginning and $
for end of string like this:
^\\d{4,12}$
or respectively /^\\d{4,12}$/
Now from the beginning to the end of the string, only 4 to 12 characters can appear.
You should use the characters ^
and $
at the start and at the end of your pattern. Doing so you state that you are looking for a string that starts with a digit and it can have any number of digits from 4 to 12.
Based on your comments and edits in your question, you may use this regex:
/^(?:[a-z]*\d){4,8}[a-z]*$/gim
RegEx Breakup:
^ - Start
(?: - Start non-capturing group
[a-z]*\d - Match 0 or more alphabets followed by a digit
){4,8} - End non-capturing group. [4,8} matches it 4 to 8 times
[a-z]* - Match trailing 0 or more alphabets in input
$ - End
Flags:
g - Global search
i - Ignore case Match
m - Multiline mode
You could check if there are 4 to 12 digits in the string with some non digits inbetween.
console.log(/^\\D*(\\d\\D*){4,12}$/.test('a78b96')); console.log(/^\\D*(\\d\\D*){4,12}$/.test('a786')); console.log(/^\\D*(\\d\\D*){4,12}$/.test('a1234567890123'));
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.