Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Regex to not allow consecutive digits at start and end but to allow middle of string

The regex ^(?!.*(d)1{5})[6-9]d{9}$ will not allow more than 5 consecutive same digits. but how to change regex to allow 6 consecutive digits in middle but not at start and end of string.

The regex should accept 6 consecutive same digits in middle of string like from 9888888654 and should not accept at the start of string like 9999994567 and at end of string like 9873555555

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a negative lookahead asserting that the string does not start or end with 6 consecutive digits.

^(?!(?:(d)1{5}|.*?(d)2{5}$))[6-9]d{9}$

In parts

  • ^ Start of the string
  • (?! Negative lookahead
    • (?: Non capture group
      • (d) Capture group 1, match 1 digit
      • 1{5} Repeat 5 times the value captured in group 1
      • | or
      • .*?(d) Match 0+ times as least a possible and capture a digit in group 2
      • 2{5}$ , repeat 5 times the value captured in group 2 till the end of the string
    • ) Close non capture group
  • ) Close lookahead
  • [6-9] Match a digit 6-9
  • d{9} Match 9 digit 0-9
  • $ End of string

Regex demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...