Regex to pick sequence of equal numbers

Asked

Viewed 2,657 times

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"

  • With at least how many digits?

  • yes, with 4 numbers at least and 15 at most

  • Were you able to solve this problem? The answers were helpful?

2 answers

5


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

That regex creates a capture group for a character typo numero and then compare that first number one or more times. The \1 takes what was captured in the first capture group and the + requires it to be the same 1 or more times.

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

jsFiddle: http://jsfiddle.net/vospcr9q/

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

  • 1

    +1 very cool. What the \1 does exactly? I’ve never seen!

  • 1

    @Wallacemaxters joined explanation and link to the regex.

  • 1

    It’s the result of the first group, if there was another group it would be 2, other languages use $1 for example. @Wallacemaxters.

  • I just asked @rray http://answall.com/questions/93996/para-que-serve-o-1-na-express%C3%A3o-regular-in-javascript

  • Okay. Either you answer my question, or I’ll have to delete :p

1

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.