简体   繁体   中英

Regex to match chars at the start and digits at the end

I need a regular expression for the following conditions:

  • The length of the string is exactly 8
  • The string may not start with PAK
  • The first character must be an upper case char [AZ]
  • The second to fourth char can be an upper case char
  • The remaining chars may only be digits

Examples:

  • PAK12345 -> not allowed
  • T1234567 -> allowed
  • ABCD1234 -> allowed
  • ABC12345 -> allowed
  • AB12345A -> not allowed
  • ABCDE123 -> not allowed
  • ABC123 -> not allowed

Actually I have the following regex:

(?!PAK)([A-Z]{1,4}[A-Z0-9]{7})$

The problem with this regex is, that "ABCDE123" is a match.

How can I say, that the first 1 to 4 characters are only upper case chars and the remaining (until the total lenght of 8) are digits?

Remove the regex range operator and do an exact character length match. Add a positive lookahead at the very first to ensure that the length must be exactly 8.

^(?=.{8}$)(?!PAK)([A-Z]{1,4}[0-9]+)$

DEMO

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