RegEx for 4 characters and 7 numbers. No special characters

Viewed 320

I'm trying to write RegEx to match some strings like ABCD1234567, 123ABC456D7 or 12A34B56C7D. There should be 4 characters and 7 digits, order is not important. And there shouldn't be any special characters like *.,- etc.

I already tried to write something like this.

^[A-Zaz]{4}[0-9]{7}$ 

Can someone help me?

2 Answers

The pattern ^[A-Zaz]{4}[0-9]{7}$ matches 4 times A-Za-z and 7 digits in that order.

You could use lookaround assertions with quantifiers instead:

^(?=(?:[^A-Za-z\r\n]*[A-Za-z]){4})(?=(?:[^0-9\r\n]*[0-9]){7})[A-Za-z0-9]+$
  • ^ Start of string
  • (?=(?:[^A-Za-z\r\n]*[A-Za-z]){4}) Assert 4 chars A-Z
  • (?=(?:[^0-9\r\n]*[0-9]){7}) Assert 7 digits
  • [A-Za-z0-9]+ Match 1+ times any of the listed or use [A-Za-z0-9]{11} to match exactly 11
  • $ End of string

Regex demo

I'd use a lookahead to check for the allowed characters and exact length and match the rest.

^(?=[A-Za-z\d]{11}$)\d*(?:\D\d*){4}$
  • (?=[A-Za-z\d]{11}$) the lookahead checks for exactly 11 [A-Za-z\d]
  • \d*(?:\D\d*){4} matches exactly 4 digits with any \D non digits in between

See this demo at regex101

Related