简体   繁体   English

正则表达式,以匹配开头的字符和末尾的数字

[英]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 字符串的长度正好是8
  • The string may not start with PAK 字符串不能以PAK开头
  • The first character must be an upper case char [AZ] 第一个字符必须是大写字符[AZ]
  • The second to fourth char can be an upper case char 第二到第四个字符可以是大写字符
  • The remaining chars may only be digits 其余字符只能是数字

Examples: 例子:

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

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. 此正则表达式的问题在于,“ ABCDE123”是一个匹配项。

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? 我怎么能说前1到4个字符只是大写字符,其余(直到8个字符)是数字?

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。

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

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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