Identify repeated numeric characters in sequence

Asked

Viewed 2,939 times

3

With the expression [\d]{9} I can identify numeric characters if they are repeated nine times in sequence, but I only want to identify if they are the same characters, for example:

111111111 // false
222222222 // false
333333333 // false
077546997 // true
123566566 // true

How this grouping should be treated?

  • 2

    (0|1|2|3|4|5|6|7|8|9){9}

  • @Brunorb would be the negation of that, should give false when this regex gives true.

3 answers

3


You can use it like this: (?!(\d)\1{8})\d{9}

Basically two parts:

  • which should not be captured: (?!(\d)\1{8})
  • the expected format of the string \d{9}

The part of Egative look Ahead that is within the tag (?! .... ) looks for strings that should not be accepted. Now making a capture group and then using this capture as reference with \1 as I explained in this other reply. Basically it takes the first number and says it must have 8 x the same number (within this negation field).

Example: https://regex101.com/r/6fv4BV/1

  • 3

    Good response Sérgio (+1)

  • 1

    Now I understand well the use of the "rear view mirror" \1 in the expression.

2

You can use the expression (\d)\1{8}.

Where:

  • (\d): Capture group, only digits 0-9.
  • \1{8}: Refers to the first capture group. It will match the same pattern matched by the capture group eight times. See details here.

console.log(/(\d)\1{8}/.test('111111111'));
console.log(/(\d)\1{8}/.test('222222222'));
console.log(/(\d)\1{8}/.test('333333333'));
console.log(/(\d)\1{8}/.test('444444444'));
console.log(/(\d)\1{8}/.test('077546997'));

Editing

The expression used in the answer will match the numbers repeated in sequence, to do the opposite, see the answers of @Sergio and @Allan!

  • 2

    I think Marcelo wants the opposite, that is 111111111 // false.

  • 2

    Good stderr response (+1)

  • 1

    The response was great, but it’s really the opposite as @Sergio replied.

  • @Sergio Really...I edited the answer and put this, I think I’ll keep the answer anyway, maybe other people have similar doubts.

  • @stderr good. Allan’s answer is basically the same as yours, he added later e negar a sua saída, which is the same that could be done with yours too.

1

One option is to use the regular expression below and deny its output:

0{9}|1{9}|2{9}|3{9}|4{9}|5{9}|6{9}|7{9}|8{9}|9{9}

Upshot:

111111111 // house

222222222 // house

333333333 // house

077546997//no house

123566566 // no house

Browser other questions tagged

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