1

I'm trying to build a regex that restricts a string for no more than 5 consecutive numeric characters and no more than 8 numeric characters in total.

For example :

  • 12345 => True
  • Yograj => True
  • Yograj123456 => False
  • 12345Yograj => True
  • 12345Yograj12345 => True
  • Yograj123456Yograj => False
  • Yograj123Varsolkar456789 => False
  • 123Yograj45678Varsolkar => True
  • A1B2C3D4e5f6g7h8i9j0 => False
  • Yograj 890 Varsolkar 78455 => False

I was able to create this till now: /^((\d{0,5}[a-zA-Z]+\d{0,5})+|\d{0,5})$/

Many thanks in advance

1 Answer 1

1

A negative lookahead with some alternation might be helpfull here:

^(?!.*\d{6}|(?:.*\d){9})[A-Za-z\d]+$

See an online demo

  • ^ - Start-line anchor.
  • (?! - Open negative lookahead:
    • .*\d{6} - 0+ Chars other than newline followed by 6 digits.
    • | - Or:
    • (?:.*\d){9} - A non-capture group of 0+ chars other than newline followed by a single digit matched 9 times.
    • ) - Close negative lookahead.
  • [A-Za-z\d]+ - Match 1+ alphanumeric characters.
  • $ - End-line anchor.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.