Home > OS >  Regex match 7 Consecutive Numbers and Ignore first and last Characters
Regex match 7 Consecutive Numbers and Ignore first and last Characters

Time:09-26

I want to test a number consisting of 9 fixed digits.

The number consists of 7 consecutive numbers in the middle. I want to ignore the first and last character. The pattern is 5YYYYYYYX

I am testing my regex using the below sample

577777773

I was able to write a regex that catches the middle 7 numbers. But i want to exclude the first and last character.

(?<!^)([0-9])\1{7}(?!$)

Any advice on how to do this

CodePudding user response:

You could write the pattern as:

(?<=^\d)(\d)\1{6}(?=\d$)

Explanation

  • (?<=^\d) Assert a digit at the start of the string to the left
  • (\d) Capture a digit in group 1
  • \1{6} Repeat the captured value in group 1 six times
  • (?=\d$) Assert a digit at the end of the string to the right

See a regex demo.

Or a capture group variant instead of lookarounds:

^\d((\d)\2{6})\d$

See another regex demo.

If the patterns should not be bounded to the start and the end of the string, you can use word boundaries \b on the left and right instead of ^ and $

CodePudding user response:

You may use this alternative solution using \B (not a word boundary):

\B(\d)\1{6}\B

RegEx Demo

RegEx Breakup:

  • \B: Inverse of word boundary
  • (\d): Match a digit and capture in group #1
  • \1{6}: Match 6 more occurrences of same digit captured in group #1
  • \B: Inverse of word boundary
  • Related