kshreve kshreve - 30 days ago 8
Javascript Question

Javscript regex with 20 chars, more than n numbers in a row

I'm trying to put two regex's together and haven't figured it out.

I've got the following to match only alphanumeric

^([a-zA-Z0-9_-]){1,20}$


and i've got the following to match any string with more than 7 numbers in a row

^\d{8,20}$


How do I put the two together to allow for only 20 alphanumeric characters, with more than 7 numbers in a row

Answer Source

You may use

/^(?=.*\d{8})[\w-]{1,20}$/

See the regex demo

Details

  • ^ - start of string
  • (?=.*\d{8}) - after any 0+ chars other than line break chars there must be 8 consecutive digits
  • [\w-]{1,20} - 1 to 20 word chars (letters, digits or _) or hyphens
  • $ - end of string.

JS demo:

var ss = ["Text_with_1234567", "Text_with_12345678"];
var rx = /^(?=.*\d{8})[\w-]{1,20}$/;
for (var s of ss) {
 console.log(s,"=>",rx.test(s));
}

NOTE:

  • If you want to make sure these 8 or more digits appear at the start of string, remove .* in the lookahead
  • If you want to make sure the digits are at the end, use (?=.*\d{8}$).