Regex to get sequence of equal numbers

5

I need to do a validation using regex, how do I validate if a string is coming with repeated numbers? for example "1111", "2222", "3333"

    
asked by anonymous 22.10.2015 / 21:44

2 answers

5

Test like this: /^(\d)+$/ .

This regex creates a capturing group for a typo number character and then compares this first number one or more times. The fetches what was captured in the first catch group and + requires that it be the same 1 or more times.

var testes = [
    '111',
    '123',
    '222',
    '334'
];
var regex = /^(\d)+$/;
var resultado = testes.map(function (str) {
    return regex.test(str);
});
alert(resultado); // true, false, true, false

jsFiddle: link

To use between 4 and 15 equal numbers you can do this : /^(\d){3,14}$/

    
22.10.2015 / 21:51
1

If you want to check if the numbers are in sequence, with 4 or more repeats, you can do this:

/^(\d\d)\d{0,4}$/.test(1222); // FALSE
/^(\d\d)\d{0,4}$/.test(122222); // TRUE

If you want to increase the validation of the sequence, simply change the value 4 of the excerpt {0,4}

    
22.10.2015 / 21:50