简体   繁体   中英

Regex match 7 Consecutive Numbers and Ignore first and last Characters

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

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 $

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM