Match specific length x or y

There is one way:

^(?=[0-9]*$)(?:.{8}|.{11})$

or alternatively, if you want to do the length check first,

^(?=(?:.{8}|.{11})$)[0-9]*$

That way, you have the complicated part only once and a generic . for the length check.

Explanation:

^       # Start of string
(?=     # Assert that the following regex can be matched here:
 [0-9]* # any number of digits (and nothing but digits)
 $      # until end of string
)       # (End of lookahead)
(?:     # Match either
 .{8}   # 8 characters
|       # or
 .{11}  # 11 characters
)       # (End of alternation)
$       # End of string

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)